如何在 MySQL 中从带有整数的字符串中获取最大值?
mysqlmysqli database更新于 2024/12/18 16:44:17
您可以使用 CAST() 和 MAX() 来实现此目的。由于字符串中填充了字符串和整数,例如"STU201",因此我们需要使用 CAST()。
首先我们创建一个表 −
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentBookCode varchar(200) ); Query OK, 0 rows affected (0.56 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable(StudentBookCode) values('STU201');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(StudentBookCode) values('STU202');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(StudentBookCode) values('STU203');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(StudentBookCode) values('STU290');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable(StudentBookCode) values('STU234');
Query OK, 1 row affected (0.15 sec)
以下是使用 select 语句显示表中的所有记录的查询 −
mysql> select *from DemoTable;
这将产生以下输出 −
+----+-----------------+ | Id | StudentBookCode | +----+-----------------+ | 1 | STU201 | | 2 | STU202 | | 3 | STU203 | | 4 | STU290 | | 5 | STU234 | +----+-----------------+ 5 rows in set (0.00 sec)
以下是获取最大值的查询 −
mysql> select MAX(CAST(SUBSTRING(StudentBookCode FROM 4) AS UNSIGNED)) from DemoTable;
这将产生以下输出 −
+----------------------------------------------------------+ | MAX(CAST(SUBSTRING(StudentBookCode FROM 4) AS UNSIGNED)) | +----------------------------------------------------------+ | 290 | +----------------------------------------------------------+ 1 row in set (0.00 sec)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

