2013-07-22 55 views
4

我有一个EXISTING表,其中有一个主键称为ID和6个其他与发票相关的字段。我需要插入旧表格中的值,并将所有值插入到新近创建的表格中。旧表格列出了发票号码,有时发票号码也有重复。我需要创建这个新列,在插入将来要插入的值时没有插入任何值时将invoice_id称为AUTO_INCREMENT,并且在现有值和未来值上插入允许重复值。当没有插入值时,它需要auto_increment。添加第二个自动增加字段,并允许重复

ID (primary) || invoice_ID (needs to auto_increment AND allow duplicates) || other colums 
1   || 1 
2   || 2 
3   || 2 
4   || 3 

我已经尝试了一些命令,这是发生了什么:

ALTER TABLE `invoices` ADD `invoice_ID` INT NOT NULL AUTO_INCREMENT AFTER `ID` , 
ADD PRIMARY KEY ( `facture`) 

结果:

MySQL said: 
#1075 - Incorrect table definition; there can be only one auto column and it must be 
defined as a key 

也试过:

ALTER TABLE `invoices` ADD `invoice_ID` INT NOT NULL AUTO_INCREMENT AFTER `ID` , 
ADD KEY ( `invoice_ID`) , 
ADD INDEX ( `invoice_ID`) 

结果:

#1075 - Incorrect table definition; **there can be only one auto column** and it must 
be defined as a key 

我也尝试了一些不同的选项,如不添加主键当然,但似乎只要我添加auto_increment请求,它使我的查询“AS PRIMARY KEY”。

回答

2

你可以用触发器来做到这一点。这是一个例子。

所以,你有你的旧表:

drop table if exists invoices_old; 
create table invoices_old (
invoice_ID int, 
another_column int 
); 

insert into invoices_old values 
(1,11), 
(2,12), 
(2,13), 
(3,14), 
(4,15), 
(5,16), 
(6,17), 
(6,18), 
(7,19); 

要插入到新表:

drop table if exists invoices_new; 
create table invoices_new (
id int not null auto_increment, 
invoice_ID int default null, /*it's important here to have a default value*/ 
another_column int, 
primary key (id) 
); 

你复制你的数据大概就是这个样子:

insert into invoices_new (invoice_ID, another_column) 
select invoice_ID, another_column 
from invoices_old; 

现在您的数据已存在于新表中,您可以在新表上创建一个触发器来模拟auto_increme nt列。

drop trigger if exists second_auto_inc; 
delimiter $$ 
create trigger second_auto_inc before insert on invoices_new 
for each row 
begin 
set @my_auto_inc := NULL; 
select max(invoice_ID) into @my_auto_inc from invoices_new; 
set new.invoice_ID = @my_auto_inc + 1; 
end $$ 
delimiter ; 

现在,当您插入更多列到新表

insert into invoices_new (another_column) 
select 20 union all select 21 union all select 22; 

,并在你的餐桌

select * from invoices_new; 

它的工作原理看看。

结果:

id invoice_ID another_column 
1 1   11 
2 2   12 
3 2   13 
4 3   14 
5 4   15 
6 5   16 
7 6   17 
8 6   18 
9 7   19 
16 8   20 
17 9   21 
18 10   22 

你可能会奇怪,为什么在现实AUTO_INCREMENT列的ID跳到9〜16有一个很好的一篇关于它这里最近SO,但我无法找到它现在。无论如何,这是你不必担心的。 Auto_increment用于确保唯一性,而不是无间隙序列。

+1

谢谢fancyPants,回答这个问题一定很费时间,我还没有完成所有的工作,但我读了,重新读了它,这比我所知道的要先进得多。我对你的回答中的描述和评论感到非常高兴。所以我开始一步步地回答你的答案,到目前为止,一切工作都很好。现在我只需要熟悉你在上面发布的这个_trigger_命令以及整段代码。再一次,谢谢你的时间。哦,我需要15点声望才能投票答复,所以尽快完成。 – Mathieu

+0

很高兴听到这个消息。如果您有更多问题,请随时询问。顺便说一句,虽然你还不能满足,你可以接受答案:) – fancyPants

相关问题