如何在 MySQL 中从包含整数的字符串中获取最大值?
你可以为此使用带有 MAX() 的 CAST()。由于字符串包含字符串和整数,例如,“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)
使用插入命令在表中插入一些记录——
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)
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP