如何使用 ORDER BY CASE WHEN REGEXP 排序查询?
使用正则表达式以及 CASE 语句。让我们先创建一个表 -
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Value varchar(20) ); Query OK, 0 rows affected (0.66 sec)
使用 insert 命令向表中插入一些记录 -
mysql> insert into DemoTable(Value) values('101'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable(Value) values('P'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable(Value) values('A'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(Value) values('53'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(Value) values('R'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(Value) values('C'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable(Value) values('190'); Query OK, 1 row affected (0.12 sec)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable;
这将会产生以下输出 -
+----+-------+ | Id | Value | +----+-------+ | 1 | 101 | | 2 | P | | 3 | A | | 4 | 53 | | 5 | R | | 6 | C | | 7 | 190 | +----+-------+ 7 rows in set (0.00 sec)
以下是使用 ORDER BY CASE 进行查询排序的查询 -
mysql> SELECT Id, Value FROM DemoTable ORDER BY CASE WHEN Value REGEXP '[a-zA-Z]' THEN 0 ELSE 0+Value END ASC, Value;
这将会产生以下输出 -
+----+-------+ | Id | Value | +----+-------+ | 3 | A | | 6 | C | | 2 | P | | 5 | R | | 4 | 53 | | 1 | 101 | | 7 | 190 | +----+-------+ 7 rows in set (0.06 sec)
广告