我有一个消息表,看起来像这样:
+------------+-------------+----------+
| sender_id | created_at | message |
+------------+-------------+----------+
| 1 | 2010-06-14 | the msg |
| 1 | 2010-06-15 | the msg |
| 2 | 2010-06-16 | the msg |
| 3 | 2010-06-14 | the msg |
+------------+-------------+----------|
我希望选择每个发送者的最新消息。
这似乎需要按sender_id分组并按created_at排序,但我无法选取最新的消息。
我正在使用postgres,因此如果我想按该字段排序,则需要在SELECT语句中对created_at字段进行聚合函数处理,因此我正在考虑像这样进行初始测试。
SELECT messages.sender_id, MAX(messages.created_at) as the_date
FROM messages
GROUP BY sender_id
ORDER BY the_date DESC
LIMIT 10;
这似乎可以工作,但当我想选择'message'时,我不知道要使用哪个聚合函数。基本上,我只想获得与最大created_at对应的消息。
有没有什么方法可以获取到它,或者我是错误的方式接近它?