在 MySQL 中,使用 CAST 运算符将 VARCHAR 列排序为 FLOAT 不起作用?

mysqlmysqli database

如果您的转换不起作用,那么您可以将 yourColumnName*1 与 ORDER BY 子句一起使用。

使用 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 排序为 float 的查询:

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)

相关文章