實現 MySQL INSERT MAX()+1?


為實現這一目的,你需要使用 COALESCE() 函式。語法如下

INSERT INTO yourTableName(yourColumnName1,yourColumnName2)
SELECT 1 + COALESCE((SELECT MAX(yourColumnName1) FROM yourTableName WHERE yourColumnName2=’yourValue’), 0), ’yourValue’;

為了理解以上語法,讓我們建立一個表。建立表的查詢如下

mysql> create table InsertMaxPlus1Demo
   -> (
   -> Id int,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (1.27 sec)

現在,你可以使用插入命令在表中插入一些記錄。查詢如下

mysql> insert into InsertMaxPlus1Demo(Id,Name) values(1,'John');
Query OK, 1 row affected (0.12 sec)
mysql> insert into InsertMaxPlus1Demo(Id,Name) values(1,'Mike');
Query OK, 1 row affected (0.21 sec)
mysql> insert into InsertMaxPlus1Demo(Id,Name) values(2,'John');
Query OK, 1 row affected (0.12 sec)
mysql> insert into InsertMaxPlus1Demo(Id,Name) values(1,'Larry');
Query OK, 1 row affected (0.20 sec)
mysql> insert into InsertMaxPlus1Demo(Id,Name) values(3,'John');
Query OK, 1 row affected (0.18 sec)
mysql> insert into InsertMaxPlus1Demo(Id,Name) values(2,'David');
Query OK, 1 row affected (0.17 sec)

使用 select 語句從表中顯示所有記錄。查詢如下

mysql> select *from InsertMaxPlus1Demo;

輸出如下

+------+-------+
| Id   | Name  |
+------+-------+
|    1 | John  |
|    1 | Mike  |
|    2 | John  |
|    1 | Larry |
|    3 | John  |
|    2 | David |
+------+-------+
6 rows in set (0.00 sec)

以下是插入 MAX()+1 的查詢

mysql> INSERT INTO InsertMaxPlus1Demo (Id, Name)
   -> SELECT 1 + coalesce((SELECT max(Id) FROM InsertMaxPlus1Demo WHERE Name='John'), 0), 'John';
Query OK, 1 row affected (0.21 sec)
Records: 1 Duplicates: 0 Warnings: 0

以上查詢正在查詢 John。ID 為 3,而記錄將使用 ID 4 插入。

現在,再次使用 select 語句檢查表記錄。查詢如下

mysql> select *from InsertMaxPlus1Demo;

輸出如下

+------+-------+
| Id   | Name  |
+------+-------+
|    1 | John  |
|    1 | Mike  |
|    2 | John  |
|    1 | Larry |
|    3 | John  |
|    2 | David |
|    4 | John  |
+------+-------+
7 rows in set (0.00 sec)

更新於: 2019 年 7 月 30 日

閱讀量 2K+

開啟您的職業生涯

透過完成課程取得認證

開始
廣告
© . All rights reserved.