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

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;


Try this

SELECT * FROM messages where id in (SELECT max(id) FROM messages GROUP BY from_id ) order by id desc


this query return last record for every Form_id:

    SELECT m1.*     FROM messages m1 LEFT JOIN messages m2     ON (m1.Form_id = m2.Form_id AND m1.id < m2.id)     WHERE m2.id IS NULL;