MySQL ORDER BY 对某些值采用不同的排序方式(降序排列,其他值则采用升序排列)?

mysqlmysqli database

您可以使用 field() 来实现这一点。让我们首先创建一个表 −

mysql> create table DemoTable
   (
   Value int
   );
Query OK, 0 rows affected (0.80 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(70);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(60);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(56);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(81);
Query OK, 1 row affected (0.44 sec)
mysql> insert into DemoTable values(85);
Query OK, 1 row affected (0.15 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable;

输出

+-------+
| Value |
+-------+
| 10    |
| 70    |
| 60    |
| 56    |
| 81    |
| 85    |
+-------+
6 rows in set (0.00 sec)

以下查询按特定 3 个值按降序排列,其余值按升序排列 −

mysql> select *from DemoTable order by field(Value,60,70,81) desc;

输出

+-------+
| Value |
+-------+
| 81    |
| 70    |
| 60    |
| 10    |
| 56    |
| 85    |
+-------+
6 rows in set (0.00 sec)

相关文章