MySQL 如何从MYSQL中的以特定字符开头的字母数字字符串的列中获取最大值

MySQL 如何从MYSQL中的以特定字符开头的字母数字字符串的列中获取最大值

为了获得最大值,使用MAX()和CAST()进行转换。由于我们想要从以特定字符开头的字符串数字中获取最大值,因此使用RLIKE。让我们先创建一个表−

mysql> create table DemoTable1381
   -> (
   -> DepartmentId varchar(40)
   -> );
Query OK, 0 rows affected (0.48 sec)

使用插入命令在表中插入一些记录−

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)

阅读更多:MySQL 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程