如何按字母顺序,然后按 MySQL 中的数字顺序排列?
你需要将正则表达式与 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)
广告