I have a messages table which looks like this:
+------------+-------------+----------+
| 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 |
+------------+-------------+----------|
I want to select the single most recent message for each sender.
This seems like a GROUP BY sender_id and ORDER BY created_at but I'm having trouble getting the most recent message selected.
I'm using postgres so need an aggregate function on the created_at field in the SELECT statement if I want to order by that field so I was looking at doing something like this as an initial test
SELECT messages.sender_id, MAX(messages.created_at) as the_date
FROM messages
GROUP BY sender_id
ORDER BY the_date DESC
LIMIT 10;
This seems to work but when I want to select 'message' as well I have no idea what aggregate function to use on it. I basically just want the message that corresponds to the MAX created_at.
Is there some way of getting at this or am I approaching it the wrong way?