我对 a similar question that was asked many years ago on StackOverflow 有一个有趣的看法
为简单起见,假设我有一个包含三列的表:
+----+------+-------+
| id | cond | value |
+----+------+-------+
| 1 | 1 | "A" |
| 2 | 0 | "B" |
| 3 | 1 | "C" |
| 4 | 0 | "D" |
| 5 | 1 | "E" |
+----+------+-------+
现在我想先按 cond
对这个表进行排序,然后按 value
ascending if cond
为 0,如果 cond
为 1,则 descending。最终排序表应如下所示:
+----+------+-------+
| id | cond | value |
+----+------+-------+
| 2 | 0 | "B" |
| 4 | 0 | "D" |
| 5 | 1 | "E" |
| 3 | 1 | "C" |
| 1 | 1 | "A" |
+----+------+-------+
请注意,我不能依赖于 value
为数字,所以我不能做一些聪明的事情,例如:
order by cond, (case when cond = 0 then value else -value end)
最佳答案
使用两个分开的条件 cond
来排序你的结果:
select *
from yourtable
order by
cond,
case when cond = 0 then `value` else 1 end,
case when cond = 1 then `value` else 1 end desc
参见 SQLFiddle DEMO 在这里。
关于mysql - 有条件地更改 SQL 中的排序方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46355177/