实现 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)
广告