MySQL 根据条件按"ENUM"类型值进行排序

mysqlmysqli database更新于 2024/2/11 22:44:00

为此,请使用 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)

相关文章