实现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。它具有ID3,并且记录将与ID4一起插入。
现在,使用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)
热门推荐
1 初八的祝福语简短
10 白羊生日祝福语 简短独特
11 生日哥哥祝福语简短独特
12 庆祝论坛周年祝福语简短
13 老婆生日祝福语短句简短
14 七姐妹新春祝福语简短
15 哥哥中考加油祝福语简短
16 幸福卡片祝福语英文简短
17 公司文案生日祝福语简短
18 科研文案祝福语简短励志