我有一个名为messages
的表格:
| id | from_id | to_id | text
+----+---------+-------+------------------
| 1 | 1 | 2 | from 1 to 2
| 2 | 2 | 1 | from 2 to 1
| 3 | 1 | 3 | from 1 to 3
| 4 | 3 | 1 | from 3 to 1
| 5 | 2 | 3 | from 2 to 3
| 6 | 1 | 2 | from 1 to 2 (2)
哪个最简单的查询可以检索用户是参与者的每个对话的最后一条消息(发件人 - from_id
还是收件人 - to_id
)?
结果应为:
| id | from_id | to_id | text
+----+---------+-------+------------------
| 4 | 3 | 1 | from 3 to 1
| 6 | 1 | 2 | from 1 to 2 (2)
这是我尝试过的:
SELECT * FROM `messages`
WHERE `id` IN (
SELECT MAX(`id`) FROM `messages`
WHERE `from_id` = 1 OR `to_id` = 1
GROUP BY `from_id`, `to_id`
)
问题在于,在用户既是发件人又是收件人的对话中,它检索用户发送的最后一条消息和用户收到的最后一条消息。
答案 0 :(得分:3)
编辑:
SELECT *
from messages
where id in
(
SELECT max(id)
FROM messages
GROUP BY CASE WHEN from_id > to_id THEN concat(from_id, 'chat', to_id)
ELSE concat(to_id, 'chat', from_id)
END
)
and (from_id = 1
or to_id = 1)
我使用子查询来获取每个聊天的最后一行:
SELECT max(id)
FROM messages
GROUP BY CASE WHEN from_id > to_id THEN concat(from_id, 'chat', to_id)
ELSE concat(to_id, 'chat', from_id)
END
您可以在SQLFiddler
中查看我更新的演示版