如何在 MySQL 中对字母数字列进行排序?

mysqlmysqli database

要对带有"100X"、"2Z"等值的字母数字列进行排序,请使用 ORDER BY。让我们首先创建一个表−

mysql> create table DemoTable
-> (
-> StudentId varchar(100)
-> );
Query OK, 0 rows affected (0.52 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable values('2X');
Query OK, 1 row affected (0.21 sec)

mysql> insert into DemoTable values('100Y');
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable values('100X');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable values('2Z');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values('2Y');
Query OK, 1 row affected (0.23 sec)

mysql> insert into DemoTable values('100Z');
Query OK, 1 row affected (0.17 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable;

输出

这将产生以下输出 −

+-----------+
| StudentId |
+-----------+
| 2X        |
| 100Y      |
| 100X      |
| 2Z        |
| 2Y        |
| 100Z      |
+-----------+
6 rows in set (0.00 sec)

这是在 MySQL 中按字母数字列排序的查询 −

mysql>select *from DemoTable order by (StudentId+0), right(StudentId, 1);

输出

这将产生以下输出 −

+-----------+
| StudentId |
+-----------+
| 2X        |
| 2Y        |
| 2Z        |
| 100X      |
| 100Y      |
| 100Z      |
+-----------+
6 rows in set, 6 warnings (0.00 sec)

相关文章