MySQL获取2人之间的最新消息

时间:2016-04-09 12:27:55

标签: mysql messaging

SELECT *
FROM messages
WHERE message_id IN (SELECT MAX(message_id)
                     FROM messages
                     GROUP BY if(sender_id > receiver_id, CONCAT(sender_id, receiver_id), CONCAT(receiver_id, sender_id))
                    )

我有一个简单的消息系统,消息是1 t 1(没有组)。 我只想获得两个用户之间的最新消息。

上述'工作'但我想我应该使用max timestamp vs message_id来获取最新版本。

我的表是:

message_id (unique, auto inc),
sender_id (Primary),
receiver_id (Primary),
time_date,
content

1 个答案:

答案 0 :(得分:1)

以下是使用correlated subquery的解决方案,该解决方案与原始查询不同(内部group by已删除。

SELECT *
FROM messages as m1
WHERE m1.time_date IN (SELECT MAX(time_date)
                     FROM messages as m2
                     WHERE (m1.sender_id = m2.sender_id and m1.receiver_id = m2.receiver_id) or 
                           (m1.sender_id = m2.receiver_id and m1.receiver_id = m2.sender_id)    
                    )