按不同的列排序

时间:2012-10-25 12:23:52

标签: mysql sql postgresql sqlite

我在表categories

中有这些数据
id | name | post_count
 1 | A    | 10
 2 | B    | 15
 3 | C    | 8
 4 | D    | 14
 5 | E    | 1
 6 | F    | 20

我想按post_count提取前4个类别,并按name排序。

如果我这样做

SELECT * FROM categories ORDER BY post_count DESC LIMIT 4

我会按顺序获取类别:F, B, D, A,而我想要A, B, D, F

单个SQL查询是否可以实现?我怎么能这样做?

3 个答案:

答案 0 :(得分:3)

您可以使用子查询:

SELECT * FROM (SELECT * FROM 
               categories ORDER BY 
               post_count DESC LIMIT 4) AS A
ORDER BY name 

See this SQLFiddle

答案 1 :(得分:3)

select * from (

SELECT * FROM categories ORDER BY post_count DESC LIMIT 4)a
order by name

答案 2 :(得分:1)

select *
from (
    select *
    from categories
    order by post_count desc
    limit 4
) s
order by name