我有下一个查询:
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,但现在它给了我第一个..
关于如何实现这一点的任何想法?
感谢
答案 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 by
。 message
中的列来自 indeterminate 行,因此您无法控制选择哪些值。
答案 1 :(得分:-1)
按DESC顺序对其进行排序以获取最新消息。