Roman Holic Roman Holic - 4 months ago 17
SQL Question

Mysql query GROUP by and ORDER by

I have table called msg where i store all messages.
I want to select all rows with unique User but only those with MAX Id field.

Answer

http://sqlfiddle.com/#!9/9ebdc/1

you can start from finding MAX:

SELECT 
 MAX(id) max_id
FROM msg
GROUP BY user_id;

and then use it as filter:

SELECT *
FROM msg
WHERE id IN (
SELECT 
 max(id) max_id
FROM msg
GROUP BY user_id);
Comments