所以希望问题不会被问到,但我没有找到。
我的示例表如下所示:https://imgur.com/a/BBykp
对于我的SQL,我知道例如用户ID为1,我想显示我的Messanger的收件箱,我需要知道用户ID 1是收到邮件还是邮件的发件人。
例如:
sender_id receiver_id
1 2
3 1
1 4
12 1
应该为ID 1提供四个收件箱结果。
所以我现在坚持
SELECT * FROM chats AS tm
WHERE tm.id IN
(SELECT MAX(id) FROM chats WHERE sender_id = 1 OR receiver_id = 1 GROUP BY receiver_id)
这让我: https://imgur.com/a/P665T
你会看到我不需要ID 2,但我关心ID 3,因为这是该对话的最新消息。
那么如何用SQL决定我想要最新的sender_id 1还是receiver_id 1?
谢谢!
答案 0 :(得分:1)
一个选项使用最少/最大的技巧:
SELECT t1.*
FROM chats t1
INNER JOIN
(
SELECT
LEAST(sender_id, receiver_id) AS sender_id,
GREATEST(sender_id, receiver_id) AS receiver_id,
MAX(updated_at) AS max_updated_at
FROM chats
GROUP BY
LEAST(sender_id, receiver_id),
GREATEST(sender_id, receiver_id)
) t2
ON LEAST(t1.sender_id, t1.receiver_id) = t2.sender_id AND
GREATEST(t1.sender_id, t1.receiver_id) = t2.receiver_id AND
t1.updated_at = t2.max_updated_at;
答案 1 :(得分:0)
SELECT * FROM chats AS tm WHERE tm.id IN(SELECT MAX(id)FROM chats WHERE sender_id = 1 OR receiver_id = 1 GROUP BY receiver_id)
你可以尝试像这样的Top(1)
SELECT id FROM chats WHERE sender_id = 1 OR receiver_id = 1 ORDER BY ID DESC
限制1
这是聊天中包含id为1的发送者或接收者的最后一行
是第一个aproximation(它不是最理想的)