0

我有这张桌子(叫它tableA):

id (PK, autoincrement)
field1 (integer)
field2 (integer)

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

INSERT INTO tableA (field1, field2)
SELECT *something*, tableB.field2
FROM tableB;

现在,我需要field1在每一行中填充一个新整数,类似于id填充方式(类似于“ MAX(field1)+1”)。有没有办法做到这一点,也许使用子查询?

4

2 回答 2

1

I am not 100% sure that there isn't any concurrency issue here, but I would start with a trigger like this:

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 |

See some examples on this fiddle.

于 2013-01-04T20:27:58.270 回答
0

我想出了这个:

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

这个想法是首先获取 MAX 值field1,将其存储在一个变量中,然后在每个选定的行上递增它。

于 2013-01-04T19:59:53.980 回答