在 SQL 中从值为字符串数字(如 Value440、Value345 等)的列中获取最大值
mysqlmysqli database更新于 2024/3/15 9:45:00
为此,您可以将 MAX() 与 substring() 一起使用。让我们首先创建一个表 −
mysql> create table DemoTable1337 -> ( -> Value varchar(50) -> ); Query OK, 0 rows affected (0.58 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable1337 values('Value400'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable1337 values('Value345'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1337 values('Value567'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable1337 values('Value489'); Query OK, 1 row affected (0.22 sec)
使用 select 语句显示表中的所有记录 −
mysql> select * from DemoTable1337;
这将产生以下输出 −
+----------+ | Value | +----------+ | Value400 | | Value345 | | Value567 | | Value489 | +----------+ 4 rows in set (0.00 sec)
以下是在 MySQL 中查找列为 varchar 时最大值的查询 −
mysql> select max(cast(substring(Value, 6) as decimal(10,2))) as MaximumValue from DemoTable1337;
这将产生以下输出 −
+--------------+ | MaximumValue | +--------------+ | 567.00 | +--------------+ 1 row in set (0.04 sec)