我有3個表,一個Child,一個Parent和一個GrandParent。子項有一個指向Parent(多對一關係)的列(parentId)。 Parent有一個指向GrandParent(另一個多對一)的列(grandParentId)。當我插入GrandParent和Parent時,他們都工作。但是,當我插入到Child時,它會因「外鍵約束」違規而失敗。2級多對一關係的mysql外鍵違規
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
兩個祖父母和父行與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上運行 – Eric 2012-03-26 06:35:15