我有两张 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/