MySQL选择多次出现的一行

时间:2018-09-09 12:01:42

标签: mysql sql

我有一个聊天行,我想从多行中取一行(最好是最后一行)。

数据库看起来像这样...

This is the image of the messages in that database row

我需要获取用户与其他人之间的最后一次对话(DISTINCT)并显示在记录集中

我们与之交谈的每个用户有一个结果。

这是我目前所拥有的:

N

谢谢。

1 个答案:

答案 0 :(得分:1)

对于用户5,您需要每其他用户最后一行。另一个用户是:

case when sender_id = 5 then receiver_id else sender_id end 

完整查询:

select *
from chat
where (sender_id = 5 or receiver_id = 5)
and (case when sender_id = 5 then receiver_id else sender_id end, message_date_time) in
(
  select
    case when sender_id = 5 then receiver_id else sender_id end as other_user,
    max(message_date_time)
  from chat
  where sender_id = 5 or receiver_id = 5
  group by case when sender_id = 5 then receiver_id else sender_id end
);

从MySQL 8.0开始,您可以使用ROW_NUMBER来按日期时间对其他用户的记录进行排名。

select *
from
(
  select
    chat.*,
    row_number() over (
      partition by case when sender_id = 5 then receiver_id else sender_id end
      order by message_date_time desc, id desc) as rn
  from chat
  where sender_id = 5 or receiver_id = 5
) ranked
where rn = 1;