如何按一列分组但选择最后一个值

时间:2013-08-20 13:10:13

标签: mysql groupwise-maximum

这是我的消息数据库 enter image description here

我想通过receiver_id进行分组,这是我的SQL

SELECT * FROM messages WHERE sender_id=2
ORDER BY created_at DESC 
GROUP BY receiver_id 
HAVING COUNT(receiver_id)>=1

它正常运作但始终显示主题Bokcreated_at=2013-08-19 20:49:22 我想展示最新的created_at和subject,在本例中为2013-08-20 14:29:41

这是我的输出

enter image description here

2 个答案:

答案 0 :(得分:0)

SELECT 
         m1.* 
FROM 
         messages m1 
LEFT JOIN 
         messages m2
ON 
    (m1.receiver_id = m2.receiver_id 
     AND m1.created_at < m2.created_at)
WHERE 
    m2.created_id IS NULL;

答案 1 :(得分:0)

Groupwise maximum帮助了我http://dev.mysql.com/doc/refman/5.0/en/example-maximum-column-group-row.html 所以我的查询看起来像

...WHERE created_at=(SELECT MAX(created_at) as created_at FROM mg_messages t2 WHERE t.receiver_id=t2.receiver_id)...