如何从以字母数字字符串开头的列中获取最大值,该列以MYSQL中的特定字符开头?
要获得最大值,请使用MAX()
和CAST()
进行转换。由于我们要从以特定字符开头的字符串中获取最大值,因此请使用RLIKE。让我们首先创建一个表-
mysql> create table DemoTable1381 -> ( -> DepartmentId varchar(40) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1381 values('IT794'); mysql> insert into DemoTable1381 values('AT1034'); mysql> insert into DemoTable1381 values('IT967'); mysql> insert into DemoTable1381 values('IT874'); mysql> insert into DemoTable1381 values('AT967');
使用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)