mysql - 有条件地更改 SQL 中的排序方向

标签 mysql sorting

我对 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/

相关文章:

mysql - 如何将数据从 CSV 导入 MySQL?

mysql - SQL查询问题转MySQL

r - 对 R data.table 的每一列进行排序

php - 如何按某个键对多维数组进行排序?

java - 如何按字母顺序对 "ArrayList<HashMap<String, String>> arrList "进行排序?

PHP MySQL 表帮助

c# - 使用 linq 删除代码时出现错误

java - 排序本地日期时间

python - 先按字母排序包含字母数字项目的列表

mysql - Qt MySQL 无法加载插件驱动(QLibrary、QPluginLoader 成功加载,QSqlDatabase::drivers() 返回空!)