Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL select distinct order by id [closed]

I have a table like the following:

id category
1  A
2  A
3  B
4  B
5  C
6  C

If I want to select the top 2 distinct categories ordered by id descending, what's the right query in mysql? I tried select distinct category from table order by id desc limit 2 but that gave me the following result:

category
C
C

instead of

category
C
B
like image 652
user366810 Avatar asked Oct 31 '25 19:10

user366810


1 Answers

By top 2, you seem to mean the ones at the end of the list. Try this:

select category
from t
group by category
order by max(id) desc
limit 2

If you mean the ones with the most rows.

Try this:

select category
from t
group by category
order by count(*) desc
limit 2

You can also include the count(*) in the select list to see what the counts are.

like image 185
Gordon Linoff Avatar answered Nov 03 '25 09:11

Gordon Linoff