为此,请使用ORDER BY CASE WHEN语句。
让我们创建一个表-
mysql> create table demo51 −> ( −> id int not null auto_increment primary key, −> name varchar(20) −> );
借助insert命令将一些记录插入表中-
mysql> insert into demo51(name) values('John'); mysql> insert into demo51(name) values('Bob'); mysql> insert into demo51(name) values('David'); mysql> insert into demo51(name) values('Sam');
使用select语句显示表中的记录-
mysql> select *from demo51;
这将产生以下输出-
+----+-------+ | id | name | +----+-------+ | 1 | John | | 2 | Bob | | 3 | David | | 4 | Sam | +----+-------+ 4 rows in set (0.00 sec)
以下是根据条件下订单的查询-
mysql> select *from demo51 −> order by −> case when name="John" then 110 −> when name="Bob" then 105 −> when name="David" then 104 −> else 101 −> end;
这将产生以下输出-
+----+-------+ | id | name | +----+-------+ | 4 | Sam | | 3 | David | | 2 | Bob | | 1 | John | +----+-------+ 4 rows in set (0.00 sec)