我很难从桌子上找到合适的排。 我试图通过查找电子邮件来获取一些行,并且我希望将最后一封电子邮件发送给他们。 我的疑问是:
select *
from persons p2, (
SELECT p.id,p.name,p.email
FROM persons p, emails e
WHERE p.id = e.person_id
) a
where a.email = p2.email
此查询返回发送给个人的所有电子邮件的列表。
有人可以帮我查询此查询,查询需要返回带有电子邮件的人员列表,但每封电子邮件需要出现一次。
谢谢
答案 0 :(得分:2)
尝试此变体:
select p.*, tmp.email
from persons p, (select person_id, email
from emails e1
where not exists (
select 1
from emails e2
where e1.person_id = e2.person_id
and e1.time_sent < e2.time_sent)) tmp
where p.id = tmp.person_id;
答案 1 :(得分:0)
如果您的DBMS支持ctes,您可以执行以下操作:
;WITH CTE
AS
(
SELECT
RANK() OVER(PARTITION BY person_id ORDER BY time_sent DESC) AS iRank,
e.email,
e.person_id
FROM
email AS e
)
SELECT
*
FROM
persons AS p
LEFT JOIN CTE
ON p.id=CTE.person_id
AND CTE.iRank=1
答案 2 :(得分:0)
这个怎么样?
select *
from persons, (SELECT p.id, m.mail, max(m.time_sent)
from persons as p, emails as m
where m.mail = p.mail
GROUP BY p.id, m.mail) as a
where persons.id = a.id