我有一个EXISTING表,其中包含一个名为ID的主键和其他与发票相关的其他字段.我需要插入旧表中的值并将所有值插入到新的但最近创建的表中.旧表中列出了发票编号,有时发票编号有重复.我需要这个我正在尝试创建的新列,当没有为将来插入的值插入值时调用invoice_id到AUTO_INCREMENT,并且在现有值和未来值上允许DUPLICATES.如果没有插入值,则需要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”.
最佳答案 你可以用触发器来做.这是一个例子.
所以你有你的旧桌子:
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_increment列.
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用于确保唯一性,而不是无间隙序列.