REGEXP时,如何使用ORDER BY CASE排序查询?
将正则表达式与CASE语句一起使用。让我们首先创建一个表-
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Value varchar(20) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(Value) values('101'); mysql> insert into DemoTable(Value) values('P'); mysql> insert into DemoTable(Value) values('A'); mysql> insert into DemoTable(Value) values('53'); mysql> insert into DemoTable(Value) values('R'); mysql> insert into DemoTable(Value) values('C'); mysql> insert into DemoTable(Value) values('190');
使用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)
以下是使用ORDERBYCASE对查询进行排序的查询-
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)