【发布时间】:2017-12-19 01:15:54
【问题描述】:
我有 3 个表,一个 Child、一个 Parent 和一个 GrandParent。 Child 有一个列 (parentId) 指向 Parent(多对一关系)。 Parent 有一个列 (grandParentId) 指向 GrandParent(另一个多对一)。当我插入 GrandParent 和 Parent 时,它们都可以工作。但是,当我插入 Child 时,它会因违反“外键约束”而失败。
create table Child (
id bigint not null auto_increment unique,
attr1 int,
parentId bigint not null,
primary key (id)
);
create table Parent (
id bigint not null auto_increment unique,
attr1 int,
grandParentId bigint not null,
primary key (id)
);
create table GrandParent (
id bigint not null auto_increment unique,
attr1 int,
primary key (id)
);
alter table Child
add constraint FK102016375B091
foreign key (parentId)
references Parent (id);
alter table Parent
add constraint FKB99B04C56B478365
foreign key (grandParentId)
references GrandParent (id);
insert into GrandParent(attr1) values(1); # created GrandParent(id)=1
insert into Parent(attr1, grandParentId) values(2, 1); #created Parent(id=1)
insert into Child(attr1, parentId) values(3, 1); #fails
GrandParent 和 Parent 行都是使用 id=1 创建的。最后一条语句失败并出现以下错误(t1 是一个新数据库)。
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`t1`.`child`, CONSTRAINT `FK102016375B091` FOREIGN KEY (`parentId`) REFERENCES `Parent` (`id`))
如果我删除父表中的父到祖父约束,则第三条语句有效。
感谢您的帮助!
【问题讨论】:
-
我在 mac 上运行 5.5.10 MySQL Community Server
标签: mysql foreign-keys constraints many-to-one