Mysql

將自動增量添加到 id 已經是外鍵的一部分

  • April 7, 2018

我想為autoincrement我的所有表添加屬性在. 但是,它們中的大多數都是約束的一部分。在沒有外鍵約束的情況下,有沒有其他方法可以做到這一點,屬性和約束?columns``id``schema``foreign key``dropping``adding``autoincrement``re-creating``foreign key

非常感謝!

嘗試臨時禁用外鍵(確保同時不允許更新數據庫):

create table t1 (id int not null primary key) engine = innodb;
create table t2 (id int not null primary key
               ,t1_id int not null
               ,    constraint abc foreign key (t1_id) 
                                   references t1 (id) 
) engine = innodb;

set foreign_key_checks = 0;
alter table t1 change column id id int auto_increment;
set foreign_key_checks = 1;

請注意,set foreign_key_checks = 1;它不會驗證外鍵,因此如果有人在禁用外鍵時設法添加無效值,您最終會得到一個不一致的數據庫:

insert into t1 (id) values (1);
set foreign_key_checks = 0;
insert into t2 (id, t1_id) values (1,1);
insert into t2 (id, t1_id) values (2,2); -- invalid
set foreign_key_checks = 1; -- does not validate foreign keys

依稀記得添加外鍵的時候也是這樣,不過這個bug好像已經修復了,因為:

select @@version;
+-----------------+
| @@version       |
+-----------------+
| 10.2.14-MariaDB |
+-----------------+
1 row in set (0.00 sec)

alter table t2 drop foreign key abc;
alter table t2 add constraint abc foreign key (t1_id)                                      references t1 (id);
ERROR 1452 (23000): Cannot add or update a child row: 
a foreign key constraint fails ("test"."#sql-5fa_a", 
CONSTRAINT "abc" FOREIGN KEY ("t1_id")
REFERENCES "t1" ("id"))

引用自:https://dba.stackexchange.com/questions/90162