MySQL 5.7.18:外键约束和ALTER TABLE CHANGE COLUMN从NULL到NOT NULL

nde*_*uma 6 mysql foreign-keys alter-table

下面的SQL脚本工作与MySQL 17年5月16日及以上,但与一个我的MySQL 5.7.18设施(另一个中,MySQL 5.7.18在泊坞窗容器推出,是OK以及)

drop table if exists bar;
drop table if exists foo;

create table foo (foo_id int not null primary key, description varchar(32));
insert into foo values ("1", "foo-one");
insert into foo values ("2", "foo-two");

create table bar (bar_id int not null primary key, foo_id int null, description varchar(32), foreign key (foo_id) references foo(foo_id));
insert into bar values ("1", "1", "bar-one");
insert into bar values ("2", "1", "bar-two");

alter table bar change column foo_id foo_id int not null;
Run Code Online (Sandbox Code Playgroud)

错误消息是:

Error Code: 1832. Cannot change column 'foo_id': used in a foreign key constraint 'bar_ibfk_1'
Run Code Online (Sandbox Code Playgroud)

问题似乎是将外键约束从NULL更改为NOT NULL.

我知道我可以将最后一个语句包装在"SET foreign_key_checks ..."调用中,但我感兴趣的是在这种情况下是否有任何系统变量或配置设置会影响MySQL的行为,因为我无法解释两个5.7.18实例之间的不同行为.

小智 5

您可以将FOREIGN_KEY_CHECKS设置为零

SET FOREIGN_KEY_CHECKS = 0;

alter table bar change column foo_id foo_id int not null;

SET FOREIGN_KEY_CHECKS = 1;
Run Code Online (Sandbox Code Playgroud)