我需要一个有条件的 ORDER BY
语句。用外行的话来说就是这样:
IF index_order IS NULL ORDER BY id ASC ELSE ORDER BY index_order ASC.
基本上,它会首先按 ID 对具有 NULL index_order 值的所有行进行排序,然后按 index_order 对其余行进行排序。
如有任何帮助,我们将不胜感激。
最佳答案
只需使用:
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
为 null 的地方首先排序,并解析与 id
升序排序的平局。然后按非空 index_order
升序排序。
我不确定我是否从您的描述中理解您希望它以不同方式排序。
关于MYSQL 条件 ORDER BY 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23438052/