2013-01-04 33 views
0

我有此表的INSERT(字段1)+1(称之为tableA):生成MAX与多行

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

我想从另一个表中插入一些记录,像这样:

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

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

回答

0

我想出了这一点:

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

的想法是得到field1 MAX值第一,它存储在一个变量,然后增加它在每个所选行。

+0

所有的答案都与变量的说明:),不错的工作 –

1

我不是100%肯定没有这里的任何并发的问题,但我会用这样的触发启动:

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 | 

查看this fiddle一些例子。

+0

+1我肯定学到了一些新的阅读! – cambraca