MySQL 排序字符串数字?
若要排序字符串数字,请使用 MySQL 中的 CAST() 函数。语法如下 −
SELECT *FROM yourTableName ORDER BY (yourColumnName as Decimal(integerValue,integerValueAfterDecimalPoint)) desc;
为了理解上述语法,我们首先创建一个表。创建表的查询如下 −
mysql> create table SortingStringDemo -> ( -> Amount varchar(10) -> ); Query OK, 0 rows affected (0.91 sec)
使用插入命令在表中插入一些记录。查询如下。
mysql> insert into SortingStringDemo values('12.34'); Query OK, 1 row affected (0.21 sec) mysql> insert into SortingStringDemo values('124.50'); Query OK, 1 row affected (0.56 sec) mysql> insert into SortingStringDemo values('9.59'); Query OK, 1 row affected (0.20 sec) mysql> insert into SortingStringDemo values('150.68'); Query OK, 1 row affected (0.17 sec) mysql> insert into SortingStringDemo values('600.54'); Query OK, 1 row affected (0.11 sec)
使用 select 语句显示表中的所有记录。查询如下。
mysql> select *from SortingStringDemo;
以下是输出。
+--------+ | Amount | +--------+ | 12.34 | | 124.50 | | 9.59 | | 150.68 | | 600.54 | +--------+ 5 rows in set (0.00 sec)
以下是对字符串数字进行降序排序的查询。
mysql> select *from SortingStringDemo order by cast(Amount as Decimal(6,2)) desc;
以下是输出。
+--------+ | Amount | +--------+ | 600.54 | | 150.68 | | 124.50 | | 12.34 | | 9.59 | +--------+ 5 rows in set (0.00 sec)
广告