MySQL获取按日期排序的唯一对话和最后一条消息

我正在制作一个邮件系统。我想检索按日期排序的特定用户与内容的对话(该用户可以是发送者或接收者)。我在网上寻找了每个问题,但没有一个按预期工作。 这是表格数据示例。

+-----+---------+-------+---------+------------+
| id  |from_user|to_user| content |   msg_date |
+-----+---------+-------+---------+------------+
|  1  |    5    |    2  | test1   | 2019-12-01 |
|  2  |    2    |    5  | test2   | 2019-12-02 |
|  3  |    2    |    7  | test3   | 2019-12-03 |
|  4  |    2    |    7  | test4   | 2019-12-04 |
|  5  |    5    |    2  | test5   | 2019-12-05 |
|  6  |    7    |    2  | test6   | 2019-12-06 |
|  7  |    7    |    2  | test7   | 2019-12-07 |
|  8  |    5    |    2  | test8   | 2019-12-08 |
+-----+---------+-------+---------+------------+

这就是我的期望。 (假设特定的用户ID为2)

+-----+---------+-------+---------+------------+
| id  |from_user|to_user| content |   msg_date |
+-----+---------+-------+---------+------------+
|  7  |    2    |    7  | test7   | 2019-12-07 |
|  8  |    5    |    2  | test8   | 2019-12-08 |
+-----+---------+-------+---------+------------+

谢谢

womenzhelihaiyouyu22 回答:MySQL获取按日期排序的唯一对话和最后一条消息

您可以使用相关子查询进行过滤,该子查询可以提取每次对话的最新消息的日期:

select t.*
from mytable t
where 
    2 in (from_user,to_user)
    and t.msg_date = (
        select max(t1.msg_date)
        from mytable t1
        where 
            least(t1.from_user,t1.to_user) = least(t.from_user,t.to_user)
            and greatest(t1.from_user,t1.to_user) = greatest(t.from_user,t.to_user)
    )

Demo on DB Fiddle

id | from_user | to_user | content | msg_date  
-: | --------: | ------: | :------ | :---------
 7 |         7 |       2 | test7   | 2019-12-07
 8 |         5 |       2 | test8   | 2019-12-08
本文链接:https://www.f2er.com/2952828.html

大家都在问