繁体   English   中英

从MySQL数据库表中获取最后一个对话行

[英]Get Last conversation row from MySQL database table

我在MYSQL中有一个数据库,它的聊天表如下所示。

在此处输入图片说明

我正在使用此查询来获取这些记录

SELECT * FROM (
    SELECT * FROM `user_chats`
    WHERE sender_id =2 OR receiver_id =2
    ORDER BY id DESC
) AS tbl
GROUP BY sender_id, receiver_id 

但我的要求是只有5,4个ID的记录。 基本上我的要求id提取了2个用户之间的最后一次对话。 这里,在2和3之间的用户对话中有2条记录,我们只希望其中的最后一条记录,即id = 5,这里不需要id = 2。

那么我们如何为该结果编写查询呢?

SELECT 
 * 
FROM 
 user_chats uc 
WHERE
 not exists ( 
   SELECT 
    1 
   FROM 
     user_chats uc2 
   WHERE 
     uc2.created > uc.created AND 
     (
       (uc.sender_id = uc2.sender_id AND uc.reciever_id = uc2.reciever_id) OR  
       (uc.sender_id = uc2.reciever_id AND uc.reciever_id = uc2.sender_id)
     )
  )

以下内容可满足您的最新记录 (假设id越大,创建时间越晚),即可满足您的条件

SELECT * FROM `user_chats`
WHERE (`sender_id` =2 AND `receiver_id` =3) OR (`sender_id` =3 AND `receiver_id` =2)
ORDER BY `id` DESC
LIMIT 1

如果id是主键,并且它与created值一起上升,那将是一个好主意。 否则(如果不确定createdid增加),将ORDER BY行替换为以下内容:

ORDER BY `created` DESC

此外,在这两种情况下, 换上正确的索引id (如果它是你的主键,那么就没有必要把更多的指标就可以了), sender_idreceiver_id (最好是综合指数,意为两列单指数), created (如果要使用ORDER BY created DESC而不是ORDER BY id DESC ,则不需ORDER BY id DESC )。

尝试GROUP BY LEAST(sender_id, receiver_id), GREATEST(sender_id, receiver_id)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM