实现 MySQL INSERT MAX()+1?

mysqlmysqli database更新于 2025/1/29 16:44:17

您需要使用 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)

现在您可以使用 insert 命令在表中插入一些记录。查询如下:

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)

相关文章


有用资源