MySql如何获取要在聊天对话列表中显示的记录

时间:2013-07-22 11:38:47

标签: mysql sql

我有单个聊天表,如图所示。我想像facebook风格一样对聊天列表进行分组。Table after selecting the conversations of user 2

此处用户2已登录,并且使用

选择了他的对话
SELECT * 
FROM  `chat`  `t` 
WHERE  `from` =2
OR  `to` =2
ORDER BY sent DESC

但在这里我想要2和任何其他用户之间的最新单项。其中2可以来自或来自列。作为最终结果,它应该返回2个条目,分别为id 25和17。

2 个答案:

答案 0 :(得分:5)

SELECT * , (
r.from + r.to
) AS dist
FROM (

SELECT * 
FROM  `cometchat` t
WHERE (
t.from =2
OR t.to =2
)
ORDER BY t.sent DESC
)r
GROUP BY dist
ORDER BY r.sent DESC

答案 1 :(得分:1)

试试这个

SELECT * 
FROM  `chat`  `t` 
WHERE id IN (SELECT MAX(s.id) FROM chat s WHERE s.`from` =2
OR  s.`to` =2 GROUP BY (IF(s.`from`=2, s.`to`, s.`from`)))
ORDER BY sent DESC