在 MySQL 中,先按字母顺序排列,然后按数字排列?
mysqlmysqli database
您需要使用带有 ORDER BY 子句的正则表达式。语法如下:
SELECT *FROM yourTableName ORDER 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) -> ); Query OK, 0 rows affected (0.95 sec)
使用 insert 命令在表中插入一些记录。 查询语句如下:
mysql> insert into AlphabetFirstThenNumberDemo(Name) values('John'); Query OK, 1 row affected (0.37 sec) mysql> insert into AlphabetFirstThenNumberDemo(Name) values('Bob'); Query OK, 1 row affected (0.21 sec) mysql> insert into AlphabetFirstThenNumberDemo(Name) values('1Sam'); Query OK, 1 row affected (0.17 sec) mysql> insert into AlphabetFirstThenNumberDemo(Name) values('Carol'); Query OK, 1 row affected (0.22 sec) mysql> insert into AlphabetFirstThenNumberDemo(Name) values('2Larry'); Query OK, 1 row affected (0.31 sec) mysql> insert into AlphabetFirstThenNumberDemo(Name) values('David'); Query OK, 1 row affected (0.27 sec) mysql> insert into AlphabetFirstThenNumberDemo(Name) values('3Mike'); Query OK, 1 row affected (0.14 sec) mysql> insert into AlphabetFirstThenNumberDemo(Name) values('Robert'); Query OK, 1 row affected (0.10 sec)
现在,您可以使用 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)