所以假设我有以下表格:人和工资。这是一种1-N关系,一个人可以有多于一份工资。
**Person**
id
name
**Wage**
id
person_id
amount
effective_date
现在,我想查询所有人及其最新工资的列表。我可以通过执行以下查询来获得结果:
SELECT
p.*,
( SELECT w.amount
FROM wages a w
WHERE w.person_id = p.id
ORDER BY w.effective_date
LIMIT 1
) as wage_amount,
( SELECT w.effective_date
FROM wages a w
WHERE w.person_id = p.id
ORDER BY w.effective_date
LIMIT 1
) as effective_date
FROM person as p
问题是,我的查询将有来自不同表的多个子查询。我想让它尽可能有效。除了使用子查询,是否有其他方法可以更快地得到相同的结果?
最佳答案
适当的索引可能会使您的版本有效地工作(即,索引wages(person_id, effective_date)
)。
下面使用单个子查询生成相同的结果:
SELECT p.*, w.amount, w.effective_date
from person p left outer join
(select person_id, max(effective_date) as maxdate
from wages
group by personid
) maxw
on maxw.person_id = p.id left outer join
wages w
on w.person_id = p.id and w.effective_date = maxw.maxdate;
这个版本可能比上面的版本更好地使用索引:
SELECT p.*, w.amount, w.effective_date
from person p left outer join
wages w
on w.person_id = p.id
where not exists (select * from wages w2 where w2.effective_date > w.effective_date);
请注意,当两个“工资”具有相同的最大有效日期时,这些版本将返回单个行的多行。