SQL中的手动排序

时间:2012-11-01 19:48:27

标签: mysql sql

如果我有一张桌子......

ThingName | ThingCategory
-------------------------
thing 1   | cat1
thing 2   | cat2
thing 3   | cat3

如何选择先按cat2排序,然后cat1,然后cat3

这甚至可能吗?

3 个答案:

答案 0 :(得分:5)

select *
from Things
order by case
    when ThingCategory = 'cat2' then 1
    when ThingCategory = 'cat1' then 2
    when ThingCategory = 'cat3' then 3
    else 4 -- Might want the default case, too
end

答案 1 :(得分:1)

完全有可能。只需通过比较订购:

ORDER BY
  ThingCategory = "cat2" DESC,
  ThingCategory = "cat1" DESC,
  ThingCategory = "cat3" DESC

答案 2 :(得分:0)

你可以这样做

SELECT ThingName , ThingCategory
    FROM yourtabe
    ORDER BY 
     CASE
        WHEN ThingCategory = 'cat2' THEN 1
        WHEN ThingCategory = 'cat1' THEN 2
        WHEN ThingCategory = 'cat3' THEN 3
    END