根据条件在 MySQL 中对记录进行排序
为此,你可以使用 ORDER BY IF()。我们首先创建一个表 −
mysql> create table DemoTable ( Name varchar(50), Score int ); Query OK, 0 rows affected (0.72 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values('Chris',98); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('David',45); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('Bob',56); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Sam',89); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Carol',78); Query OK, 1 row affected (0.14 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
这将生成以下输出 −
+-------+-------+ | Name | Score | +-------+-------+ | Chris | 98 | | David | 45 | | Bob | 56 | | Sam | 89 | | Carol | 78 | +-------+-------+ 5 rows in set (0.00 sec)
以下是根据条件在 MySQL 中对记录进行排序的查询 −
mysql> select *from DemoTable order by if(Name='Sam',1,0) ASC,Score DESC;
这将生成以下输出 −
+-------+-------+ | Name | Score | +-------+-------+ | Chris | 98 | | Carol | 78 | | Bob | 56 | | David | 45 | | Sam | 89 | +-------+-------+ 5 rows in set (0.00 sec)
广告