如何在 MySQL 中按 DESC 或 ASC 顺序对 varchar 数值列进行排序?
首先创建一张表 −
mysql> create table DemoTable726 (Value varchar(100)); Query OK, 0 rows affected (0.60 sec)
使用插入命令在表中插入一些记录 −
mysql> insert into DemoTable726 values('100'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable726 values('10'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable726 values('110'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable726 values('2000'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable726 values('1000'); Query OK, 1 row affected (0.14 sec)
使用 select 语句从表中显示所有记录 −
mysql> select *from DemoTable726;
将生成以下输出 -
+-------+ | Value | +-------+ | 100 | | 10 | | 110 | | 2000 | | 1000 | +-------+ 5 rows in set (0.00 sec)
以下是按升序排序 varchar 数值列的查询 −
mysql> select *from DemoTable726 order by CAST(Value AS DECIMAL(20,2));
将生成以下输出 -
+-------+ | Value | +-------+ | 10 | | 100 | | 110 | | 1000 | | 2000 | +-------+ 5 rows in set (0.00 sec)
以下是按降序排序并显示结果的查询 −
mysql> select *from DemoTable726 order by CAST(Value AS DECIMAL(20,2)) DESC;
将生成以下输出 -
+-------+ | Value | +-------+ | 2000 | | 1000 | | 110 | | 100 | | 10 | +-------+ 5 rows in set (0.00 sec)
广告