Last Updated: February 25, 2016
·
730
· rayfranco

Ordering and Grouping with MySQL

Let's say I want to get the last posts from each categories on my blog. I would first give a try with this :

SELECT p.* FROM Posts p GROUP BY p.category_id ORDER BY p.created_at DESC;

Then realize that ORDER BY is happening after the GROUP BY, which is not what we want. Placing the GROUP BY is not possible either.

This is the solution to ORDER BY before a GROUP BY:

SELECT p.* FROM (SELECT * from Posts ORDER BY created_at DESC) as p GROUP BY p.category_id;