MySQL中基于条件的ORDER BY记录
为此,您可以使用ORDERBYIF()
。让我们首先创建一个表-
mysql> create table DemoTable ( Name varchar(50), Score int );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('Chris',98); mysql> insert into DemoTable values('David',45); mysql> insert into DemoTable values('Bob',56); mysql> insert into DemoTable values('Sam',89); mysql> insert into DemoTable values('Carol',78);
使用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)