首先用 MySQL ORDER BY 设置一个固定值?


我们先创建一个表格 -

mysql> create table DemoTable
   -> (
   -> Number int
   -> );
Query OK, 0 rows affected (0.57 sec)

使用 insert 命令向表格中插入一些记录 -

mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values(12);
Query OK, 1 row affected (0.22 sec)

mysql> insert into DemoTable values(14);
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values(19);
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values(45);
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values(56);
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable values(103);
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable values(87);
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values(98);
Query OK, 1 row affected (0.12 sec)

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

mysql> select *from DemoTable;

输出

这将产生以下输出 -

+--------+
| Number |
+--------+
| 10     |
| 20     |
| 12     |
| 14     |
| 19     |
| 45     |
| 56     |
| 103    |
| 87     |
| 98     |
+--------+
10 rows in set (0.00 sec)

以下是使用 ORDER BY 首先对特定值进行排序的查询 -

mysql− select *from DemoTable order by (Number=45) DESC,Number;

输出

这将产生以下输出 -

+--------+
| Number |
+--------+
| 45     |
| 10     |
| 12     |
| 14     |
| 19     |
| 20     |
| 56     |
| 87     |
| 98     |
| 103    |
+--------+
10 rows in set (0.00 sec)

更新于:30-6-2020

1K+ 浏览

开启您的 职业生涯

完成课程即可获得认证

入门
广告