维护 MySQL 中传递的 ID 的自定义顺序
若要维护 ID 的自定义顺序,请使用 ORDER BY CASE 语句。我们首先创建一个表 -
mysql> create table DemoTable1550 -> ( -> Id int, -> Name varchar(20) -> ); Query OK, 0 rows affected (0.61 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable1550 values(101,'Chris'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable1550 values(110,'Bob'); Query OK, 1 row affected (0.29 sec) mysql> insert into DemoTable1550 values(105,'Carol'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1550 values(109,'Mike'); Query OK, 1 row affected (0.17 sec)
使用 select 语句显示表中的所有记录 -
mysql> select * from DemoTable1550;
这将产生以下输出 -
+------+-------+ | Id | Name | +------+-------+ | 101 | Chris | | 110 | Bob | | 105 | Carol | | 109 | Mike | +------+-------+ 4 rows in set (0.00 sec)
以下是维护传递的 ID 顺序的查询 -
mysql> select * from DemoTable1550 -> where Id IN(109,101,110) -> order by case Id -> when 109 then 1001 -> when 101 then 1002 -> when 110 then 1003 -> end;
这将产生以下输出 -
+------+-------+ | Id | Name | +------+-------+ | 109 | Mike | | 101 | Chris | | 110 | Bob | +------+-------+ 3 rows in set (0.00 sec)
广告