MySQL 5.7.18:外键约束和ALTER TABLE CHANGE COLUMN从NULL到NOT NULL
问题描述:
以下SQL脚本适用于MySQL 5.16.17及更早版本,但不适用于我的MySQL 5.7.18安装中的一个(另一个一个时,MySQL 5.7.18在泊坞窗容器推出,是OK以及)MySQL 5.7.18:外键约束和ALTER TABLE CHANGE COLUMN从NULL到NOT NULL
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;
的错误信息是:似乎
Error Code: 1832. Cannot change column 'foo_id': used in a foreign key constraint 'bar_ibfk_1'
的问题需要改变一列从一个外键约束NULL为NOT NULL。
我知道我可以在“SET foreign_key_checks ...”调用中包装最后一条语句,但我对这种情况下是否存在影响MySQL行为的系统变量或配置设置感兴趣,因为我无法解释两个5.7.18实例之间的不同行为。
答
可以设置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;
我无法重现该问题。你可以告诉我们'SQL_MODE'变量的值。请参阅[db-fiddle](https://www.db-fiddle.com/f/xtPue5iZnMoHhR5S7cBQKZ/2)。 – wchiquito
的sql_mode在5.7.18本地安装: NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION 的sql_mode在5.7.18泊坞容器: ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION (是的,我禁用了本地STRICT_TRANS_TABLES看看这是否有任何效果,但无济于事) – ndeuma
使用db-fiddle时,代码片断失败,并且使用5.6和5.7运行。有趣... – ndeuma