使用数字对 MySQL 字符串进行排序?


要对带数字的 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)
   -> );
Query OK, 0 rows affected (0.86 sec)

使用插入命令向表中插入一些记录。查询如下 −

mysql> insert into OrderByStringWithNumbers(Words) values('A10');
Query OK, 1 row affected (0.19 sec)

mysql> insert into OrderByStringWithNumbers(Words) values('A30');
Query OK, 1 row affected (0.19 sec)

mysql> insert into OrderByStringWithNumbers(Words) values('A12');
Query OK, 1 row affected (0.13 sec)

mysql> insert into OrderByStringWithNumbers(Words) values('A11');
Query OK, 1 row affected (0.17 sec)

mysql> insert into OrderByStringWithNumbers(Words) values('A28');
Query OK, 1 row affected (0.13 sec)

mysql> insert into OrderByStringWithNumbers(Words) values('A21');
Query OK, 1 row affected (0.20 sec)

使用 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)

更新于:30-6-2020

5K+ 浏览量

开启你的 职业 生涯

完成该课程以获得认证

开始
广告