簡體   English   中英

MySQL左連接從一個表中選擇最高值

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

我有下一個查詢:

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,但是現在它給了我第一個。

關於如何實現這一目標的任何想法?

謝謝

使用子查詢獲取聊天的最后消息時間,並將其加入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的方式使用group by message的列來自不確定的行,因此您無法控制選擇哪個值。

按DESC順序對其進行排序以獲取最新消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM