uollaa uollaa - 3 months ago 8
MySQL Question

Select ONLY one row per category

Ok I have siple table which contains data:

id cat_id title (with random values)

1 1 test
2 1 tstt
3 3 tewt
4 2 4324
5 3 rterter


Now, I need to create a query which selects only ONE raw per category (cat_id)
(possibly with lowest ID and ordered by cat_id)

So the result should be:

1 1 test
4 2 4324
3 3 tewt

Answer

Use GROUP BY :

SELECT MIN(id), cat_id, title FROM table GROUP BY cat_id
Comments