如何在 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)

更新於: 2019 年 7 月 30 日

3K+ 瀏覽量

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告