在单个查询中按特定条件升序/降序排序

Order by ascending / descending with certain condition in single query

我有一个 table 如下:

+-----+-------------+
| id  | status_code |
+-----+-------------+
|  1  |         200 |
|  2  |         301 |
|  3  |         404 |
|  4  |         404 |
|  5  |           0 |
|  6  |         200 |
|  7  |         200 |
+-----+-------------+

如何在单个查询中得到下面的结果?

1) 按状态码降序排列,但 0 在结果的顶部。

+-----+-------------+
| id  | status_code |
+-----+-------------+
|  5  |           0 |
|  4  |         404 |
|  3  |         404 |
|  2  |         301 |
|  7  |         200 |
|  6  |         200 |
|  1  |         200 |
+-----+-------------+

2) 按状态码升序排列,但结果末尾为0。

+-----+-------------+
| id  | status_code |
+-----+-------------+
|  1  |         200 |
|  6  |         200 |
|  7  |         200 |
|  2  |         301 |
|  3  |         404 |
|  4  |         404 |
|  5  |           0 |
+-----+-------------+

0 位居榜首:

ORDER BY status_code = 0 DESC, status_code DESC

获得底部0

ORDER BY status_code = 0 ASC, status_code ASC

这是有效的,因为比较运算符 return 0 用于 false1 用于 true.

只需包含多个键。在 MySQL 中,这很容易:

order by (status_code = 0) desc, status_code desc

第一种情况。

order by (status_code = 0) asc, status_code asc

第二个

这是如何工作的? MySQL 将布尔表达式视为数字上下文中的整数,0 为假,1 为真。所以,(status = 0) 变成 0 或 1。ascdesc 只是决定哪个先到。

你可以这样试试:-

select * from yourtable 
order by (status_code = 0) desc, status_code desc