Select ONLY one row for each category.

Good. I have a table containing 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 that only selects ONE raw for each category (cat_id) (possibly with the smallest ID and ordered cat_id)

Thus, the result should be:

 1 1 test 4 2 4324 3 3 tewt 
+4
source share
2 answers

Use GROUP BY :

 SELECT MIN(id), cat_id, title FROM table GROUP BY cat_id 
+7
source
 SELECT a.* FROM tableName a INNER JOIN ( SELECT cat_id, MIN(id) id FROM tableName GROUP BY cat_id ) b ON a.cat_id = b.cat_id AND a.id = b.id ORDER BY a.cat_id 
+1
source

Source: https://habr.com/ru/post/1494284/


All Articles