使用 CAST 运算符将 VARCHAR 列排为 FLOAT 在 MySQL 中无法运作?
如果您的强制转换不起作用,您可以与 ORDER BY 子句一起使用 yourColumnName*1。
使用 yourColumnName*1。语法如下
SELECT yourColumnName1,yourColumnName2,...N FROM yourTableName ORDER BY yourColumnName*1 DESC;
您还可以使用 CAST() 运算符。语法如下
SELECT yourColumnName1,yourColumnName2,...N FROM yourTableName ORDER BY CAST(yourColumnName as DECIMAL(8,2)) DESC;
为了理解以上语法,让我们创建一个表格。创建表格的查询如下
mysql> create table VarcharColumnAsFloatDemo -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Amount varchar(20), -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (1.01 sec)
使用 insert 命令在表格中插入一些记录。查询如下
mysql> insert into VarcharColumnAsFloatDemo(Amount) values('3446.23'); Query OK, 1 row affected (0.10 sec) mysql> insert into VarcharColumnAsFloatDemo(Amount) values('2464.46'); Query OK, 1 row affected (0.16 sec) mysql> insert into VarcharColumnAsFloatDemo(Amount) values('6465.78'); Query OK, 1 row affected (0.13 sec) mysql> insert into VarcharColumnAsFloatDemo(Amount) values('6464.98'); Query OK, 1 row affected (0.44 sec) mysql> insert into VarcharColumnAsFloatDemo(Amount) values('645.90'); Query OK, 1 row affected (0.19 sec) mysql> insert into VarcharColumnAsFloatDemo(Amount) values('6465.99'); Query OK, 1 row affected (0.23 sec) mysql> insert into VarcharColumnAsFloatDemo(Amount) values('3745.76'); Query OK, 1 row affected (0.14 sec)
使用 select 语句显示表格中的所有记录。查询如下
mysql> select *from VarcharColumnAsFloatDemo;
以下是输出
+----+---------+ | Id | Amount | +----+---------+ | 1 | 3446.23 | | 2 | 2464.46 | | 3 | 6465.78 | | 4 | 6464.98 | | 5 | 645.90 | | 6 | 6465.99 | | 7 | 3745.76 | +----+---------+ 7 rows in set (0.00 sec)
以下是使用强制转换运算符将 varchar 作为浮点型排序的查询
mysql> select Id,Amount from VarcharColumnAsFloatDemo order by cast(Amount as DECIMAL(8,2)) DESC;
以下是输出
+----+---------+ | Id | Amount | +----+---------+ | 6 | 6465.99 | | 3 | 6465.78 | | 4 | 6464.98 | | 7 | 3745.76 | | 1 | 3446.23 | | 2 | 2464.46 | | 5 | 645.90 | +----+---------+ 7 rows in set (0.00 sec)
第二种方法如下,使用 yourColumnName*1
mysql> select Id,Amount from VarcharColumnAsFloatDemo order by Amount*1 desc;
以下是输出
+----+---------+ | Id | Amount | +----+---------+ | 6 | 6465.99 | | 3 | 6465.78 | | 4 | 6464.98 | | 7 | 3745.76 | | 1 | 3446.23 | | 2 | 2464.46 | | 5 | 645.90 | +----+---------+ 7 rows in set (0.00 sec)
广告