简体   繁体   English

MySQL左连接从一个表中选择最高值

[英]mysql left join select top value from one table

I have the next query: 我有下一个查询:

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

now, I want to pick the newest message.time, but right now it gives me the first one.. 现在,我想选择最新的message.time,但是现在它给了我第一个。

any idea on how this could be accomplished? 关于如何实现这一目标的任何想法?

thanks 谢谢

Use a subquery to get the last message time for the chat and join that back to the message table: 使用子查询获取聊天的最后消息时间,并将其加入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;

Do not use group by the way you were using it. 不要按使用group by的方式使用group by The columns from message come from indeterminate rows, so you have no control over which values are chosen. message的列来自不确定的行,因此您无法控制选择哪个值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM