在MySQL中先按字母顺序排列,然后按数字顺序排列?
您需要将正则表达式与ORDER BY子句一起使用。语法如下:
SELECT *FROM yourTableNameORDER BY IF(yourColumnName RLIKE '^[a-z]', 1, 2),yourColumnName;
为了理解上述语法,让我们创建一个表。创建表的查询如下:
mysql> create table AlphabetFirstThenNumberDemo-> (
-> Id int NOT NULL AUTO_INCREMENT,
-> Name varchar(20),
-> PRIMARY KEY(Id)
-> );
使用insert命令在表中插入一些记录。查询如下:
mysql> insert into AlphabetFirstThenNumberDemo(Name) values('John');mysql> insert into AlphabetFirstThenNumberDemo(Name) values('Bob');
mysql> insert into AlphabetFirstThenNumberDemo(Name) values('1Sam');
mysql> insert into AlphabetFirstThenNumberDemo(Name) values('Carol');
mysql> insert into AlphabetFirstThenNumberDemo(Name) values('2Larry');
mysql> insert into AlphabetFirstThenNumberDemo(Name) values('David');
mysql> insert into AlphabetFirstThenNumberDemo(Name) values('3Mike');
mysql> insert into AlphabetFirstThenNumberDemo(Name) values('Robert');
现在,您可以使用select语句显示表中的所有记录。查询如下:
mysql> select *from AlphabetFirstThenNumberDemo;
以下是输出:
+----+--------+| Id | Name |
+----+--------+
| 1 | John |
| 2 | Bob |
| 3 | 1Sam |
| 4 | Carol |
| 5 | 2Larry |
| 6 | David |
| 7 | 3Mike |
| 8 | Robert |
+----+--------+
8 rows in set (0.00 sec)
这是查询顺序,首先是字母,然后是数字。查询如下:
mysql> select *from AlphabetFirstThenNumberDemo-> ORDER BY IF(Name RLIKE '^[a-z]', 1, 2),Name;
以下是输出:
+----+--------+| Id | Name |
+----+--------+
| 2 | Bob |
| 4 | Carol |
| 6 | David |
| 1 | John |
| 8 | Robert |
| 3 | 1Sam |
| 5 | 2Larry |
| 7 | 3Mike |
+----+--------+
8 rows in set (0.00 sec)
以上是 在MySQL中先按字母顺序排列,然后按数字顺序排列? 的全部内容, 来源链接: utcz.com/z/352434.html