执行相同字段的排序顺序的 MySQL 查询
为此,请使用 ORDER BY IF()。
首先让我们创建一个表 −
mysql> create table DemoTable801 ( Score int ); Query OK, 0 rows affected (0.69 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable801 values(30); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable801 values(99); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable801 values(45); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable801 values(55); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable801 values(99); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable801 values(69); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable801 values(25); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable801 values(79); Query OK, 1 row affected (0.12 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable801;
这会产生以下输出 -
+-------+ | Score | +-------+ | 30 | | 99 | | 45 | | 55 | | 99 | | 69 | | 25 | | 79 | +-------+ 8 rows in set (0.00 sec)
以下查询用于执行同一字段的排序顺序 −
mysql> select *from DemoTable801 order by if(Score=99,1,0), Score;
这会产生以下输出 -
+-------+ | Score | +-------+ | 25 | | 30 | | 45 | | 55 | | 69 | | 79 | | 99 | | 99 | +-------+ 8 rows in set (0.00 sec)
广告