MYSQL条件ORDER BY语句

时间:2014-05-02 22:45:48

标签: mysql sql-order-by

我需要一个条件ORDER BY语句。通俗地说,就像这样:

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

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

非常感谢任何帮助。

2 个答案:

答案 0 :(得分: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升序排序。

我不确定我是否从您的描述中理解您希望如何对其进行不同的排序。

答案 1 :(得分:0)

你可以使用COALESCE和NULLIF:

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

点击herehere

了解更多信息