mysql如何按用户定义的顺序排序
说一个表
---------+----------
name | category
---------+----------
apple | 0
orange | 0
book | 1
notebook | 1
textboo | 1
phone | 2
如何按以下类别顺序排序,即category = 1,category = 0,category = 2 获得视图
---------+----------
name | category
---------+----------
book | 1
notebook | 1
textbook | 1
apple | 0
orange | 0
phone | 2
我们如何为此编写SQL?
另外更好的是,如果语句可以根据每个类别的项目数识别和排序desc。
答案 0 :(得分:7)
你想这样做:
SELECT Name, Category
FROM MyTable
ORDER BY
Case category
when 1 then 1
when 0 then 2
else 3
end,
Name
<强>更新强>
在第一个答案中,订单按类别确定。按类别中的项目数排序时,您希望这样做:
select name, Category,
(select count(*) from MyTable mt2 where mt2.Category = mt1.category) CatCount
from MyTable mt1
order by 3 DESC, name
答案 1 :(得分:3)
如果要按类别中的条目数排序,可以执行以下操作:
SELECT my_table.name, my_table.category, cats.total FROM
(SELECT category, COUNT(*) AS total FROM my_table GROUP BY category) cats
INNER JOIN my_table ON my_table.category = cats.category
ORDER BY cats.total DESC, my_table.name ASC
答案 2 :(得分:0)
如果您在编写查询时知道订单,则可以使用UNION ALL:
SELECT name, category
FROM table
WHERE category = 1
UNION ALL
SELECT name, category
FROM table
WHERE category = 0
UNION ALL
SELECT name, category
FROM table
WHERE category = 2