如何在MySQL中按DESC或ASC对varchar数字列进行排序?
让我们首先创建一个表-
mysql> create table DemoTable726 (Value varchar(100));
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable726 values('100'); mysql> insert into DemoTable726 values('10'); mysql> insert into DemoTable726 values('110'); mysql> insert into DemoTable726 values('2000'); mysql> insert into DemoTable726 values('1000');
使用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)