I have a table with user comments in a guestbook. Columns are: id, user_id, title, comment, timestamp.
I need to select the latest row for each user. I have tried t
You can build on your query using a JOIN:
select c.*
from comments c join
(select user_id, max(ts) as maxts
from comments c2
group by user_id
) cc
on c.user_id = cc.user_id and c.ts = cc.maxts;
There are other ways. Typical advice is to use row_number():
select t.*
from (select c.*, row_number() over (partition by user_id order by ts desc) as seqnum
from comments c
) c
where seqnum = 1;
These two queries are subtly different. The first will return duplicates if the most recent comment for a user had exactly the same ts. The second returns one row per user.