如何从以特定字符开头的字母数字字符串的列中获取最大值?
对于最大值,将 MAX() 与 CAST() 一起用于转换。由于我们希望从以特定字符开头的字符串数字中获取最大值,因此使用 RLIKE。我们首先创建一个表 −
mysql> create table DemoTable1381 -> ( -> DepartmentId varchar(40) -> ); Query OK, 0 rows affected (0.48 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable1381 values('IT794'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable1381 values('AT1034'); Query OK, 1 row affected (0.52 sec) mysql> insert into DemoTable1381 values('IT967'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1381 values('IT874'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable1381 values('AT967'); Query OK, 1 row affected (0.09 sec)
使用 select 语句显示表中的所有记录 −
mysql> select * from DemoTable1381;
这将产生以下输出 −
+--------------+ | DepartmentId | +--------------+ | IT794 | | AT1034 | | IT967 | | IT874 | | AT967 | +--------------+ 5 rows in set (0.00 sec)
以下是查询,可以从以特定字符(此处为“IT”)开头的字母数字字符串的列中获取最大值 −
mysql> select max(cast(substr(trim(DepartmentId),3) AS UNSIGNED)) from DemoTable1381 where DepartmentId RLIKE 'IT';
这将产生以下输出 −
+-----------------------------------------------------+ | max(cast(substr(trim(DepartmentId),3) AS UNSIGNED)) | +-----------------------------------------------------+ | 967 | +-----------------------------------------------------+ 1 row in set (0.10 sec)
广告