如何在 MySQL 中对字母数字列进行排序?
mysqlmysqli database更新于 2025/5/17 19:56:17
要对带有"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)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

