Reputation: 3279
I have this data, in a table categories
id | name | post_count
1 | A | 10
2 | B | 15
3 | C | 8
4 | D | 14
5 | E | 1
6 | F | 20
I want to fetch the top 4 categories, by post_count
, and order them by name
.
If I do
SELECT * FROM categories ORDER BY post_count DESC LIMIT 4
I'll get the categories in order: F, B, D, A
, while I want A, B, D, F
Is this possible with a single SQL query? How can I do this?
Upvotes: 0
Views: 76
Reputation: 24046
select * from (
SELECT * FROM categories ORDER BY post_count DESC LIMIT 4)a
order by name
Upvotes: 3
Reputation: 125294
select *
from (
select *
from categories
order by post_count desc
limit 4
) s
order by name
Upvotes: 1
Reputation: 32602
You can use sub-query:
SELECT * FROM (SELECT * FROM
categories ORDER BY
post_count DESC LIMIT 4) AS A
ORDER BY name
Upvotes: 3