【问题标题】:Get the latest record by date for a user in MySQL在 MySQL 中按日期获取用户的最新记录
【发布时间】:2015-02-05 08:25:54
【问题描述】:

我有两张桌子

user_conversation
-----------------
id
from_user_id
to_user_id
item_id
offer_detail_id
message_type
deleted_by_sender
deleted_by_receiver

user_conversation_reply
-----------------------
id
from_user_id
message_text
sent_date
conversation_id
is_read

每当针对任何项目开始新对话时,都会在 user_conversation_table 中输入一条记录,并且该对话的消息将记录在 user_conversation_reply 表中。同样,可以在 user_conversation_table 中为该对话添加不同的消息。

我想获取用户的所有对话。 (即 from_user_id,to_user_id,item_id 组成一个组合)以及我需要有此对话的最后一条消息。

user_conversation 

id     from_user_id     to_user_id     item_id
1           8              2             1

user_conversation_reply 

id     from_user_id     message     conversation_id   sent_date
1           8              helo             1         2014-12-07
2           8           how r u             1         2014-12-08

一个用户可以参与多个对话。因此,我想获取用户每个对话的最后一个对话消息。

我正在使用此查询来过滤掉用户的记录。

Select * from user_conversation where to_user_id = 2;

请,建议。

谢谢, 费萨尔·纳西尔

【问题讨论】:

    标签: mysql greatest-n-per-group


    【解决方案1】:

    假设user_conversation_reply.id 是一个自动递增的主键,
    而且最后一条消息总是最高的id

    SELECT *
    FROM (
      Select uc.id, max( ucr.id ) max_ucr
      from user_conversation uc
      JOIN user_conversation_reply ucr ON ucr.conversation_id = uc.id
      where uc.to_user_id = 2
      GROUP BY uc.id
    ) q
    JOIN user_conversation uc ON q.id = uc.id
    JOIN user_conversation_reply ucr ON q.max_ucr = ucr.id
    ;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      • 2014-03-10
      • 1970-01-01
      • 2014-03-25
      相关资源
      最近更新 更多