簡體   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