社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  DATABASE

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

kenarsuleyman • 5 年前 • 1494 次点击  

我在做一个信息系统。我想检索特定用户的对话内容(此用户可以是发送者或接收者)按日期排序。我在网上查找了每个问题,但没有一个能像预期的那样工作。 下面是示例表数据。

+-----+---------+-------+---------+------------+
| 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 |
+-----+---------+-------+---------+------------+

谢谢

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51023
 
1494 次点击  
文章 [ 1 ]  |  最新文章 5 年前
GMB
Reply   •   1 楼
GMB    5 年前

您可以使用关联的子查询进行筛选,该子查询提取每个会话的最新消息的日期:

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