使用 MySQL 是否能够按升序对同时具有字符串和数字值的 varchar 数据进行排序?
mysqlmysqli database更新于 2025/10/4 0:44:17
为此,您可以使用 ORDER BY IF(CAST())。让我们首先创建一个表 −
mysql> create table DemoTable(EmployeeCode varchar(100)); Query OK, 0 rows affected (1.17 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values('190');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('100');
Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values('120');
Query OK, 1 row affected (0.21 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+--------------+ | EmployeeCode | +--------------+ | 190 | | 100 | | John | | 120 | +--------------+ 4 rows in set (0.00 sec)
以下是使用字符串和数字值 − 对 varchar 数据进行升序排序的查询
mysql> select *from DemoTable ORDER BY IF(CAST(EmployeeCode AS SIGNED) = 0, 100000000000, CAST(EmployeeCode AS SIGNED));
这将产生以下输出。这里,数字首先被排序 −
+--------------+ | EmployeeCode | +--------------+ | 100 | | 120 | | 190 | | John | +--------------+ 4 rows in set, 1 warning (0.00 sec)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

