根据条件对 MySQL 中“ENUM”类型的字段进行 ORDER BY
为此,使用 ORDER BY CASE 语句。我们首先创建一个表,其中有一个 ENUM 类型的列 -
mysql> create table DemoTable1461 -> ( -> DeckOfCards ENUM('K','J','A','Q') -> ); Query OK, 0 rows affected (0.64 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable1461 values('K'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable1461 values('A'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable1461 values('J'); Query OK, 1 row affected (0.44 sec) mysql> insert into DemoTable1461 values('Q'); Query OK, 1 row affected (0.13 sec)
使用 select 语句显示表中的所有记录 -
mysql> select * from DemoTable1461;
这将产生以下输出 -
+-------------+ | DeckOfCards | +-------------+ | K | | A | | J | | Q | +-------------+ 4 rows in set (0.00 sec)
以下是按 ENUM 类型的字段值排序的查询 -
mysql> select * from DemoTable1461 -> order by -> case DeckOfCards when 'A' then 100 -> when 'K' then 101 -> when 'Q' then 102 -> else 103 -> end;
这将产生以下输出 -
+-------------+ | DeckOfCards | +-------------+ | A | | K | | Q | | J | +-------------+ 4 rows in set (0.00 sec)
广告