我对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
升序 排序,如果cond
为0且<如果cond
为1,则强> 降序 。最终排序表应如下所示:
+----+------+-------+
| 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)
答案 0 :(得分:3)
使用两个分开的条件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 。
答案 1 :(得分:1)
按值排序后添加行号。然后进行条件排序:
select *
from (
select a.*, @r := @r + 1 AS rn
from (
select *
from mytable
order by value) a
join (select @r := 0) b) a
order by cond, (case when cond then -rn else rn end)
将排序转换为int的另一种方法:
select a.*, count(b.id) c
from mytable a
join mytable b on a.cond = b.cond and a.value > b.value
group by a.id
order by a.cond, case when a.cond then -c else c end