Select N rows grouped by foreign key

40 Views Asked by At

Suppose I have a simple table called Articles which has three columns id, category_id, title. I want to select the 3 newest rows for each category_id, thus giving me the latest articles for each category.

Kind of the equivalent of:

SELECT * FROM articles WHERE category_id = 1 ORDER BY id LIMIT 3
UNION
SELECT * FROM articles WHERE category_id = 2 ORDER BY id LIMIT 3
...

I am aware that is somewhat of a duplicate, but many examples over complicate the simple query I'm trying to build and I can't get my head around the various joins, variables etc. needed to make it work.

Just want something simple :)

Many thanks!

0

There are 0 best solutions below