简体   繁体   中英

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..

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:

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. The columns from message come from indeterminate rows, so you have no control over which values are chosen.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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