Mysql 生成最大值(字段1)和#x2B;1在具有多行的插入上

Mysql 生成最大值(字段1)和#x2B;1在具有多行的插入上,mysql,Mysql,我有这张桌子(称之为tableA): 我想从另一个表中插入一些记录,如下所示: INSERT INTO tableA (field1, field2) SELECT *something*, tableB.field2 FROM tableB; CREATE TRIGGER ins_your_table BEFORE INSERT ON your_table FOR EACH ROW SET new.field1=case when new.field1 is null then

我有这张桌子(称之为
tableA
):

我想从另一个表中插入一些记录,如下所示:

INSERT INTO tableA (field1, field2)
SELECT *something*, tableB.field2
FROM tableB;
CREATE TRIGGER ins_your_table BEFORE INSERT ON your_table 
FOR EACH ROW
  SET new.field1=case when new.field1 is null then
      coalesce((select max(field1)+1 from your_table),1)
    else new.field1 end
;

insert into your_table (field1, field2) values (10, 1),(11, 2),(12, 3);

select * from your_table;

| ID | FIELD1 | FIELD2 |
------------------------
|  1 |     10 |      1 |
|  2 |     11 |      2 |
|  3 |     12 |      3 |

delete from your_table;

insert into your_table (field1, field2) values (10, 1),(11, 2),(12, 3);
insert into your_table (field2) values (4),(5),(6);

select * from your_table;

| ID | FIELD1 | FIELD2 |
------------------------
|  1 |     10 |      1 |
|  2 |     11 |      2 |
|  3 |     12 |      3 |
|  4 |     13 |      4 |
|  5 |     14 |      5 |
|  6 |     15 |      6 |
现在,我需要的是
field1
在每一行中填充一个新的整数,类似于
id
的填充方式(类似于“
MAX(field1)+1
”)。有没有办法做到这一点,也许可以使用子查询?

我想到了这个:

SET @newVAL = (SELECT MAX(field1) FROM tableA);
INSERT INTO tableA (field1, field2)
SELECT @newVAL := @newVAL+1, tableB.field2
FROM tableB

我们的想法是首先获取
字段1的最大值,将其存储在一个变量中,然后在每个选定的行上递增它。

我不能100%确定这里没有任何并发问题,但我会从如下触发器开始:

INSERT INTO tableA (field1, field2)
SELECT *something*, tableB.field2
FROM tableB;
CREATE TRIGGER ins_your_table BEFORE INSERT ON your_table 
FOR EACH ROW
  SET new.field1=case when new.field1 is null then
      coalesce((select max(field1)+1 from your_table),1)
    else new.field1 end
;

insert into your_table (field1, field2) values (10, 1),(11, 2),(12, 3);

select * from your_table;

| ID | FIELD1 | FIELD2 |
------------------------
|  1 |     10 |      1 |
|  2 |     11 |      2 |
|  3 |     12 |      3 |

delete from your_table;

insert into your_table (field1, field2) values (10, 1),(11, 2),(12, 3);
insert into your_table (field2) values (4),(5),(6);

select * from your_table;

| ID | FIELD1 | FIELD2 |
------------------------
|  1 |     10 |      1 |
|  2 |     11 |      2 |
|  3 |     12 |      3 |
|  4 |     13 |      4 |
|  5 |     14 |      5 |
|  6 |     15 |      6 |
请参见上的一些示例