mysql left join从一个表中选择top值

时间:2014-12-23 01:26:12

标签: mysql sql left-join

我有下一个查询:

SELECT chat.*, message.time as last_message, message.content as last_message_content 
FROM chat 
LEFT JOIN message ON chat.id = message.chat_id 
GROUP BY chat.id 
ORDER BY message.time ASC

现在,我想选择最新的message.time,但现在它给了我第一个..

关于如何实现这一点的任何想法?

感谢

2 个答案:

答案 0 :(得分:0)

使用子查询获取聊天的最后消息时间并将其连接回message表:

SELECT c.*, m.time as last_message, m.content as last_message_content 
FROM chat c LEFT JOIN
     (select chat_id, max(time) as last_message_time
      from message
      group by chat_id
     ) ml
     ON c.id = ml.chat_id LEFT JOIN
     message m
     ON m.chat_id = ml.chat_id and m.time = ml.lst_message_time
ORDER BY m.time ASC;

请勿按照您使用它的方式使用group bymessage中的列来自 indeterminate 行,因此您无法控制选择哪些值。

答案 1 :(得分:-1)

按DESC顺序对其进行排序以获取最新消息。