选择聊天对话中的最后一行

时间:2018-01-13 18:02:14

标签: mysql sql

我有一张这样的表:

+---+--------+----------+---------+
|id | sender | receiver | created |
+---+--------+----------+---------+
  1     4         9       3333
  2     9         4       3334
  3     4         9       3335
  4     5         4       3336
  5     4         9       3337

我的查询是:

SELECT *
FROM chat_messages 
WHERE sender = 4 OR receiver = 4
GROUP BY sender, receiver
ORDER BY created DESC

结果是:

+---+--------+----------+---------+
|id | sender | receiver | created |
+---+--------+----------+---------+
  5     4         9       3337
  4     5         4       3336
  2     9         4       3334

我更接近我所寻求的。我正在寻找这个结果:

+---+--------+----------+---------+
|id | sender | receiver | created |
+---+--------+----------+---------+
  5     4         9       3337
  4     5         4       3336

意思是,如果对话是用户n,则我想要最新的行,而用户nsenderreceiver的其他行。提前谢谢。

1 个答案:

答案 0 :(得分:1)

您可以在where子句中使用过滤。这是一种方法:

select cm.*
from chat_messages cm
where cm.created = (select max(cm2.created)
                    from chat_messages cm2
                    where (cm2.sender, cm2.receiver) in ( (cm.sender, cm.receiver), (cm.receiver, cm.sender))
                   ) and
      4 in (cm.receiver, cm.sender);

如果您只想要创建的时间和ID,您可能会发现聚合效果更好:

select least(cm.receiver, cm.sender),
       greatest(cm.receiver, cm.sender),
       max(cm.id), max(cm.created)
from chat_message cm
where 4 in (cm.receiver, cm.sender)
group by least(cm.receiver, cm.sender), greatest(cm.receiver, cm.sender);