我有一个非常简单但很重要的会话表(created_by是发送消息的用户的代码)。然后,我有一个conversations_messages表(sent_by是发送消息的用户的代码,消息是我的消息文本,created_at是时间戳)。最后,我有一个conversations_users表,其中包含user_id(收到消息的用户代码)和created_by(发送消息的用户代码)。
我正在尝试实现收件箱的功能,我想显示每个对话的最后一条消息。 conversations_users中的user_id是收到邮件的用户和正在查询其收件箱的用户。
我尝试了此查询,但我不知道如何处理created_at时间戳(在表conversations_messages中)以获取每个对话的最新消息。
select CM.id, CM.message, CM.created_at, C.id as 'conversation_id' from conversations_users CU
join conversations C on CU.conversation_id = C.id join conversations_messages CM on C.id = CM.conversation_id where CU.user_id = 1 and CM.created_at = '2015-03-10 14:18:02'
我必须更换2015-03-10 14:18:02'对于一些最新的created_at时间戳来说明我的问题。
我的表是:
谢谢!
答案 0 :(得分:1)
SELECT cm.*
FROM conversations_messages cm
JOIN conversations c ON cm.conversation_id = c.id
JOIN conversations_users cu ON cu.conversation_id = c.id
WHERE cu.user_id = 1
AND NOT EXISTS ( SELECT 'a'
FROM conversations_messages cm2
WHERE cm2.conversation_id = cm.conversation_id
AND cm2.created_at > cm.created_at
)
GROUP BY c.id
答案 1 :(得分:0)
以下是使用max
聚合将表格连接回自身的一种方法,按每个对话进行分组:
select CM.id, CM.message, CM.created_at, C.id as 'conversation_id'
from conversations_users CU
join conversations C on CU.conversation_id = C.id
join conversations_messages CM on C.id = CM.conversation_id
join (
select max(created_at) maxcreated_at, conversation_id
from conversations
group by conversation_id
) T on T.maxcreated_at = CM.created_at
and T.conversation_id = CM.conversation_id
where CU.user_id = 1