繁体   English   中英

检索用户是特定用户的每个对话的最后一条消息

[英]Retrieving the last message of each conversation where a user is a participent

我有一个叫做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`
)

它的问题在于,在用户既是发送者又是接收者的对话中,它检索用户发送的最后一条消息和用户收到的最后一条消息。

编辑:

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中查看我更新的演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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