按 MySQL 中选定记录排序?
可以为此使用一个 CASE 语句。我们先创建一个表格 -
mysql> create table DemoTable ( Number int ); Query OK, 0 rows affected (0.71 sec)
使用 insert 命令在表格中插入记录 -
mysql> insert into DemoTable values(490); Query OK, 1 row affected (0.35 sec) mysql> insert into DemoTable values(310); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(540); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(123); Query OK, 1 row affected (0.60 sec) mysql> insert into DemoTable values(1230); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(1090); Query OK, 1 row affected (0.43 sec)
使用 select 语句显示表格中的所有记录。查询如下 -
mysql> select * from DemoTable;
这将产生以下输出 -
+--------+ | Number | +--------+ | 490 | | 310 | | 540 | | 123 | | 1230 | | 1090 | +--------+ 6 rows in set (0.00 sec)
以下是 MySQL 中按选定记录排序的查询 -
mysql> select *from DemoTable order by (case when Number = 1090 then 0 else 1 end), Number;
这将产生以下输出 -
+--------+ | Number | +--------+ | 1090 | | 123 | | 310 | | 490 | | 540 | | 1230 | +--------+ 6 rows in set (0.00 sec)
广告