我有一个非常困难的情况,有一个SQL语句我无法弄清楚如何解决它,虽然我搜索过SO(和Get the newest entry before a GROUP BY query}
我有一张桌子:
id date from_name to_name from_id to_id message
1 2013-08-29 07:20:00 John Maria 1234 4321 hi!
2 2013-08-28 05:20:00 Justin Helen 1234 5678 Where ru?
3 2013-08-29 08:21:00 Helen Dude 5678 8765 Good!
4 2013-08-27 02:20:00 Jesus Aliko 9876 9988 where?
5 2013-08-26 02:20:00 Jesus Aliko 9876 9988 what?
通常我会用group by
做这个:
SELECT id,date,from_id,from_name,to_name,message FROM messages where to_id='9876' group by from_id order by date desc
并给我以下结果:
5 2013-08-26 02:20:00 Jesus Aliko 9876 9988 what?
这不是耶稣给Aliko的最新(最新)信息。我怎么能用最新的条目分组?
有任何帮助吗? 感谢
答案 0 :(得分:3)
这会给你你想要的东西:
select *
from messages
where to_id='9876'
and date = (select max(date) from messages where to_id='9876')
答案 1 :(得分:0)
SELECT id,date,from_id,from_name,to_name,message
FROM messages m1
WHERE to_id='9876'
AND NOT EXISTS (SELECT FROM messages m2 WHERE m2.to_id = m1.to_id and m2.date > m1.date)