对于带数字的MySQL顺序字符串,以下是语法,其中我们使用了ORDER BY,SUBSTR()
以及CAST()
-
SELECT *FROM yourTableName ORDER BY SUBSTR(yourColumnName FROM 1 FOR 2), CAST(SUBSTR(yourColumnName FROM 2) AS UNSIGNED);
为了理解上述语法,让我们创建一个表。创建表的查询如下-
mysql> create table OrderByStringWithNumbers -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Words varchar(10), -> PRIMARY KEY(Id) -> );
使用insert命令在表中插入一些记录。查询如下-
mysql> insert into OrderByStringWithNumbers(Words) values('A10'); mysql> insert into OrderByStringWithNumbers(Words) values('A30'); mysql> insert into OrderByStringWithNumbers(Words) values('A12'); mysql> insert into OrderByStringWithNumbers(Words) values('A11'); mysql> insert into OrderByStringWithNumbers(Words) values('A28'); mysql> insert into OrderByStringWithNumbers(Words) values('A21');
使用select语句显示表中的所有记录-
mysql> select *from OrderByStringWithNumbers;
以下是输出-
+----+-------+ | Id | Words | +----+-------+ | 1 | A10 | | 2 | A30 | | 3 | A12 | | 4 | A11 | | 5 | A28 | | 6 | A21 | +----+-------+ 6 rows in set (0.00 sec)
这是按编号的字符串排序的查询-
mysql> select *from OrderByStringWithNumbers order by -> substr(Words from 1 for 2), -> cast(substr(Words from 2) AS UNSIGNED);
以下是输出-
+----+-------+ | Id | Words | +----+-------+ | 1 | A10 | | 4 | A11 | | 3 | A12 | | 6 | A21 | | 5 | A28 | | 2 | A30 | +----+-------+ 6 rows in set (0.00 sec)