Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select ONLY one row per category

Tags:

mysql

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                   
like image 304
uollaa Avatar asked Jul 30 '13 12:07

uollaa


People also ask

How do I select only certain rows in SQL?

To select rows using selection symbols for character or graphic data, use the LIKE keyword in a WHERE clause, and the underscore and percent sign as selection symbols. You can create multiple row conditions, and use the AND, OR, or IN keywords to connect the conditions.

How do I select the first row in a group by a group?

To do that, you can use the ROW_NUMBER() function. In OVER() , you specify the groups into which the rows should be divided ( PARTITION BY ) and the order in which the numbers should be assigned to the rows ( ORDER BY ). You assign the row numbers within each group (i.e., year).


2 Answers

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
like image 28
John Woo Avatar answered Oct 13 '22 05:10

John Woo


Use GROUP BY :

SELECT MIN(id), cat_id, title FROM table GROUP BY cat_id
like image 125
Bart Friederichs Avatar answered Oct 13 '22 05:10

Bart Friederichs