【问题标题】:MYSQL conditional ORDER BY statementMYSQL 条件 ORDER BY 语句
【发布时间】:2014-06-19 17:21:13
【问题描述】:

我需要有条件的ORDER BY 语句。用外行的话来说是这样的:

IF index_order IS NULL ORDER BY id ASC ELSE ORDER BY index_order ASC.

所以基本上,它会首先按 ID 对 index_order 值为 NULL 的所有行进行排序,然后按 index_order 对其余行进行排序。

我们将不胜感激。

【问题讨论】:

标签: mysql sql-order-by


【解决方案1】:

只需使用:

ORDER BY index_order, id

因为 NULL 的排序总是低于任何其他值。因此,所有 index_order 为 NULL 的行都将首先分组。然后他们的订单将由id解决。


你的评论:

我试过了。

mysql> create table foo (id int auto_increment primary key, index_order int);
mysql> insert into foo values (1, 2), (2, 1), (3, null), (4, null);
mysql> select * from foo order by index_order, id;
+----+-------------+
| id | index_order |
+----+-------------+
|  3 |        NULL |
|  4 |        NULL |
|  2 |           1 |
|  1 |           2 |
+----+-------------+

它首先对index_order 为空的位置进行排序,并以id 升序解决平局。然后它按非空index_order 升序排序。

我不确定我是否从您的描述中了解您希望它如何以不同的方式排序。

【讨论】:

  • 谢谢比尔。起初我尝试过,它对我有用,但是,我需要按 ID ASC 对 NULL 行进行排序,并且在继续使用 index_order 之前似乎按 ID DESC 对它们进行排序。有什么想法吗?
  • 我想我需要指定 NULL index_order 行将按 ID 列按升序排序 - 它们移动到 index_order。正如你在上面所说的,它可以工作,只是对 NULL 行的排序与我需要的相反。
【解决方案2】:

你可以使用 COALESCE 和 NULLIF :

ORDER BY COALESCE(NULLIF(id, ''), index_order), index_order

点击herehere了解更多信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多