4

ID と呼ばれる主キーと、請求に関連する 6 つの他のフィールドを持つ EXISTING テーブルがあります。古いテーブルから値を挿入し、すべての値を新しいが最近作成されたテーブルに挿入する必要があります。古いテーブルには請求書番号が記載されており、請求書番号が重複している場合があります。作成しようとしているこの新しい列が必要です。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」になるようです。

4

1 に答える 1

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_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 は、ギャップのないシーケンスではなく、一意性を確保するためにあります。

于 2013-07-22T22:45:27.720 に答える