实现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)
   -> );

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

mysql> insert into InsertMaxPlus1Demo(Id,Name) values(1,'John');
mysql> insert into InsertMaxPlus1Demo(Id,Name) values(1,'Mike');
mysql> insert into InsertMaxPlus1Demo(Id,Name) values(2,'John');
mysql> insert into InsertMaxPlus1Demo(Id,Name) values(1,'Larry');
mysql> insert into InsertMaxPlus1Demo(Id,Name) values(3,'John');
mysql> insert into InsertMaxPlus1Demo(Id,Name) values(2,'David');

使用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';
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)