我有这个查询来获取两个用户之间的最后一条消息。
SELECT f.*
FROM
(
SELECT *
FROM messages a
WHERE (LEAST(a.sender, a.receiver), GREATEST(a.sender, a.receiver), a.timestamp)
IN (
SELECT LEAST(b.sender, b.receiver) AS x,
GREATEST(b.sender, b.receiver) AS y,
MAX(b.timestamp) AS msg_time
FROM messages b
GROUP BY x, y
)
) f
WHERE :user_id IN (f.sender, f.receiver)
ORDER BY f.timestamp DESC
我在这里得到它,对我来说有点复杂。
我需要修改它才能在:user_id
未删除会话时获取最后一条消息。
该表有4个重要字段:sender, receiver, sender_deleted, receiver_deleted
。
当用户想要删除对话时,我会运行查询以将已删除的字段设置为1。
用户4删除了会话的表格示例:
sender receiver sender_deleted receiver_deleted message
4 17 1 0 user 4 to 17 message
17 4 0 1 user 17 to 4 message
我需要修改上述查询,以便:user_id = 4
返回为空,但如果:user_id = 17
返回上次发送的消息。
我希望我能很好地解释我想做什么。
答案 0 :(得分:0)
这应该做你想要的:
SELECT f.*
FROM
(
SELECT *
FROM messages a
WHERE (LEAST(a.sender, a.receiver), GREATEST(a.sender, a.receiver), a.timestamp)
IN (
SELECT LEAST(b.sender, b.receiver) AS x,
GREATEST(b.sender, b.receiver) AS y,
MAX(b.timestamp) AS msg_time
FROM messages b
GROUP BY x, y
)
) f
WHERE (:user_id = f.sender AND f.sender_deleted != 1)
OR (:user_id = f.receiver AND f.receiver_deleted != 1)
ORDER BY f.timestamp DESC