How to get the latest record in each group using GROUP BY? [duplicate]

You should find out last timestamp values in each group (subquery), and then join this subquery to the table –

SELECT t1.* FROM messages t1
  JOIN (SELECT from_id, MAX(timestamp) timestamp FROM messages GROUP BY from_id) t2
    ON t1.from_id = t2.from_id AND t1.timestamp = t2.timestamp;

Leave a Comment