MYSQL查询:获取按数据分组的最新日期

时间:2018-09-24 11:23:30

标签: mysql sql

我有一张桌子聊天。


消息,我senderID,我,ciptantID,我,日期

我想通过对话获取有关最新消息组的查询。 (例如,如果'senderID = 1且recipentID = 2''senderID = 2且recipentID = 1'是相同的对话)

2 个答案:

答案 0 :(得分:2)

您可以使用in。 MySQL支持in的元组,因此这是一种方法:

select c.*
from chats c
where (least(senderID, recipentID), greatest(senderID, recipentID), date) in
       (select least(senderID, recipentID), greatest(senderID, recipentID), max(date)
        from chats c
        group by least(senderID, recipentID), greatest(senderID, recipentID)
       );

答案 1 :(得分:1)

  • 您可以将两个人之间的特定对话识别为“ concatenated id-LEAST id”的GREATEST字符串
  • 对“对话”进行分组以找到每个对话的Max日期(最后消息日期)。
  • 将此作为Derived table结果集,并加入到主表(使用ON(显式)和WHERE(隐式连接的类型))

尝试以下查询:

SELECT 
  CONCAT(LEAST(t1.senderID, t1.recipentID), 
         '-', 
         GREATEST(t1.senderID, t1.recipentID)) AS t1_conversation, 
  t1.*
FROM chat_table AS t1 
JOIN ( 
      SELECT CONCAT(LEAST(t2.senderID, t2.recipentID), '-', 
                    GREATEST(t2.senderID, t2.recipentID)) AS conversation, 
             MAX(t2.date) as last_message_date 
      FROM chat_table AS t2 
      GROUP BY t2.conversation
     ) AS t3 ON t3.max_date = t1.date 
WHERE t1_conversation = t3.conversation