我有单个聊天表,如图所示。我想像facebook风格一样对聊天列表进行分组。
此处用户2已登录,并且使用
选择了他的对话SELECT *
FROM `chat` `t`
WHERE `from` =2
OR `to` =2
ORDER BY sent DESC
但在这里我想要2和任何其他用户之间的最新单项。其中2可以来自或来自列。作为最终结果,它应该返回2个条目,分别为id 25和17。
答案 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