将自动增量添加到 id 已经是外键的一部分

Sum*_*ode 2 mysql foreign-key uniqueidentifier mysql-workbench auto-increment

我想补充的autoincrement属性我所有的表的columns命名idschema。然而,它们中的大多数是foreign key约束的一部分。是否有任何其他方式做到这一点不dropping为所有的外键约束,addingautoincrement财产和re-creatingforeign key约束?

非常感谢!

Len*_*art 8

尝试临时禁用外键(确保不允许同时更新数据库):

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;
Run Code Online (Sandbox Code Playgroud)

请注意,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
Run Code Online (Sandbox Code Playgroud)

我依稀记得添加外键时也是这种情况,但是这个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"))
Run Code Online (Sandbox Code Playgroud)