我有两张桌子:
聊天(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
我收到了最新的对话,但我收到了每个对话的第一条消息,而不是最后一条消息。我怎样才能收到最后一条消息?
答案 0 :(得分:3)
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
答案 1 :(得分:3)
select m1.*
from messages m1
join
(
SELECT MAX(id) as id
FROM message
GROUP BY id_chat
) m2 on m1.id = m2.id