mysql - 在 MySQL 中按日期获取用户的最新记录

标签 mysql greatest-n-per-group

我有两张 table

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;

请提出建议。

谢谢, 费萨尔·纳西尔

最佳答案

假设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
;

关于mysql - 在 MySQL 中按日期获取用户的最新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27345166/

相关文章:

MySQL Query 需要带回行,而不是空结果

SQL Server 选择每个 ID 的最大日期

java - 如何从 mysql 表中获取最后 3 个不同的 ID

mysql - 从 MySQL JSON 数组中获取不同的值

mysql - REGEX sql 查询

php - 在 Google 日历中插入事件 PHP 和 SQL

mysql - 为 AngularJS 驱动的学习页面存储数据的正确方法是什么

mysql - 加入mysql后如何按组/类别获取前n个解决方案?

mysql - 在子查询中重用联接表

sql - 如何在sql中查询每个项目的最近五笔交易