MySQL GROUP BY在DESC命令中

时间:2014-01-10 21:07:32

标签: mysql

我有一张包含以下3个字段的表格,

msg_id | conversation_id | subject
1 |   1 | 1st message
2 |   1 | 2nd message

我想获得每次谈话的最后记录。所以我写下面的查询,

SELECT max(msg_id) as msg_id,  `conversation_id` ,  `subject` 
FROM  `tbl_messages` 
GROUP BY  `conversation_id` 
ORDER BY  `msg_id` DESC 

它为我提供了msg_id 2但在subject中提供了1st message

我从max() How to group by DESC order

这个问题中获得了帮助

1 个答案:

答案 0 :(得分:2)

如果您想了解每个对话中最后一条消息的信息,那么正确的查询就是将这些信息连接在一起的查询:

select m.*
from tbl_messages m join
     (select conversation_id, max(msg_id) max_msg_id
      from tbl_messages
      group by conversation_id
     ) mc
     on m.msg_id = mc.max_msg_id;