MYSQL 条件 ORDER BY 语句

标签 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 对其余行进行排序。

如有任何帮助,我们将不胜感激。

最佳答案

只需使用:

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/

相关文章:

mysql - 在mysql中显示行号

SQL Server 按最接近零的值排序

ruby-on-rails-3 - Rails 3 : . group() 由 created_at 排序

mysql - 如何根据丰度对行进行排序?

mysql - 按多个字段排序 Magento 自定义集合

java - 根据java中特定列中的值从sql数据库中选择一行

php - 为 MySQLi 插入查询设置时区

php - 按日期和自动递增列 (id) 排序,但按第四列 (ab) 的字母顺序对第三列 (oid) 具有相同值的行进行排序

Mysql - 根据两列 : discounted_price and price 订购产品表

php - 具有条件偏好的mysql SELECT