我的数据库中有两个表:
会话:
conversationid | persone | perstwo | timestamp
1 | 1 | 3 | 1431680294000
2 | 3 | 8 | 1431680407000
消息:
messageid | conversationid | senderid | receiverid | message | timestamp | seen
1 1 1 3 Xyz! 1431680294000 0
2 2 3 8 Hi x! 1431680405000 0
3 2 3 8 Allt bra? 1431680407000 0
现在我想找到每个对话的最新消息。
我现在的方法是找到用户的对话,然后尝试按对话框进行分组:
SELECT DISTINCT conversationid, senderid, receiverid, message, timestamp
FROM message WHERE conversationid IN
(SELECT conversationid FROM conversation WHERE persone = 3 OR perstwo = 3)
GROUP BY conversationid ORDER BY timestamp DESC
不幸的是我得到了这些结果:
2 3 8 Hi x! 1431680405000
1 1 3 Xyz! 1431680294000
即使我最后一次谈话需要Allt bra?
。
我正在运行Arch of MariaDB的最新版本。
答案 0 :(得分:1)
此类问题的常见模式是查找派生表中的最后一项并与其联接以过滤主查询。在您的情况下,查询将类似于:
select *
from conversation c
join message m on c.conversationid = m.conversationid
join (
select conversationid, max(timestamp) timestamp
from Message
group by conversationid
) x on m.conversationid = x.conversationid
and x.timestamp = m.timestamp
where c.persone = 3 OR c.perstwo = 3