选择每个会话的最新消息

9udxz4iz  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(275)

我有两张table:
聊天( from 是发送第一条信息的人)

id | id_from | id_to
1  | 1       | 2
2  | 1       | 3
3  | 3       | 2
4  | 4       | 1

消息

id | content | date                | id_chat | id_from | id_to
1  | hi      | 2017-10-04 23:14:41 | 1       | 1       | 2
2  | hello   | 2017-10-04 23:15:03 | 1       | 2       | 1
3  | heey    | 2017-10-04 23:40:00 | 4       | 4       | 1

我想得到每次谈话的最后一条信息。
我试过了( 1 是用户登录的id):

SELECT MAX(id) AS idMessage, id_from, id_to, content, date 
FROM message 
WHERE 1 IN (id_from, id_to) 
GROUP BY id_chat
ORDER BY idMessage 
DESC LIMIT 10

我收到的是最新的对话,但每次对话我都会收到第一条信息,而不是最后一条。我怎样才能得到最后的消息?

tez616oj

tez616oj1#

select m1.*
from messages m1
join
(
  SELECT MAX(id) as id
  FROM message
  GROUP BY id_chat
) m2 on m1.id = m2.id
dldeef67

dldeef672#

SELECT m.content as idMessage, m.id_from, m.id_to, m.date  from message as m JOIN chat c WHERE <Logged_ID> = m.id_chat ORDER BY m.date DESC LIMIT 1

相关问题