我有三个表:用户,请求和消息。我希望获得类似android / ios消息应用程序在启动时显示的线程列表。
用户
id username 1 a 2 b 3 c
请求
id 1 2 3
消息
Id request_id sender_id receiver_id message timestamp 1 1 1 2 asd 2013-06-10 06:45 2 1 1 3 sdf 2013-06-10 06:42 3 2 1 1 dfg 2013-06-10 06:41 4 2 1 2 fgh 2013-06-11 06:40 5 2 1 2 ghj 2013-06-12 07:45 6 2 2 1 jkl 2013-06-10 06:45 7 3 3 1 zxc 2013-06-10 03:45 8 3 3 1 xcv 2013-06-10 05:45
我想得到的是这样的:
发
request_id sender_name receiver_name last_message last_timestamp 1 a b asd 2013-06-10 06:45 1 a c sdf 2013-06-10 06:42 2 a b ghj 2013-06-12 07:45 2 a a dfg 2013-06-10 06:41 3 c a xcv 2013-06-10 05:45
这里,request_id + sender_id + receiver_id对于每一行和last_message是唯一的,last_timestamp显示消息表中的最新条目。订单将是last_timestamp降序。我如何获得此表?
答案 0 :(得分:0)
您需要groupwise maximum,可以通过将Messages
表连接到子标识来找到,该子查询标识每个组的标识(最大)时间戳:
SELECT Message.request_id,
Sender.username AS sender_name,
Receiver.username AS receiver_name,
Message.message AS last_message,
Message.timestamp AS last_timestamp
FROM Message NATURAL JOIN (
SELECT request_id,
sender_id,
receiver_id,
MAX(timestamp) timestamp
FROM Message
GROUP BY request_id, sender_id, receiver_id
) t
JOIN User Sender ON Sender.id = Message.sender_id
JOIN User Receiver ON Receiver.id = Message.receiver_id
ORDER BY Message.request_id, last_timestamp DESC
在sqlfiddle上查看。
请注意,由于my comment above中突出显示的原因,我的结果集的顺序与您问题中的预期顺序不同:
您说“订单将
last_timestamp
降序”,但在给定示例中,消息'ghj'
(在所有其他消息发出两天后发送)不会显示仅在所有记录的中间,但也在所有具有相同request_id
的那些记录的中间。请澄清结果集所需的排序顺序?