我正在尝试通过最新消息在2个用户之间进行独特的对话。我迷路了。
我的表设置为
iD | From | to | Message | Read | Created_at
1 | 2 | 1 | blah1 | 0 | 2019-01-11 02:15:24
2 | 1 | 2 | blah2 | 0 | 2019-01-11 02:16:24
3 | 2 | 1 | blah3 | 0 | 2019-01-11 02:17:24
4 | 2 | 3 | blah4 | 0 | 2019-01-11 02:18:24
5 | 1 | 5 | blah5 | 0 | 2019-01-11 02:19:24
6 | 1 | 3 | blah6 | 0 | 2019-01-11 02:20:24
我希望每次对话的结果都没有重复。
例如。如果选择所有具有用户ID 1的对话,我需要这样的结果...
iD | From | to | Message | Read | Created_at
3 | 2 | 1 | blah3 | 0 | 2019-01-11 02:17:24
5 | 1 | 5 | blah5 | 0 | 2019-01-11 02:19:24
6 | 1 | 3 | blah6 | 0 | 2019-01-11 02:20:24
我尝试过的所有操作都导致1到2以及2到1的对话重复
,我在这里搜索的所有内容都不适合我。
答案 0 :(得分:1)
您可以使用该查询获取给定用户(在我的示例中,我使用的是用户1)与其他任何用户之间的最新对话时间:
SELECT CASE WHEN `From` = 1 THEN `To` ELSE `From` END AS other, MAX(Created_at) AS latest
FROM conversations
WHERE `From` = 1 OR `To` = 1
GROUP BY other
这只是将问题JOIN
添加到整个表格中以获取两个用户之间最新消息的详细信息的问题:
SELECT c.*
FROM conversations c
JOIN (SELECT CASE WHEN `From` = 1 THEN `To` ELSE `From` END AS other, MAX(Created_at) AS latest
FROM conversations
WHERE `From` = 1 OR `To` = 1
GROUP BY other) m
ON (c.From = 1 AND c.To = m.other OR c.To = 1 AND c.From = m.other) AND c.Created_at = m.latest
输出:
iD From to Message Read Created_at
3 2 1 blah3 0 2019-01-11 02:17:24
5 1 5 blah5 0 2019-01-11 02:19:24
6 1 3 blah6 0 2019-01-11 02:20:24