私は3つのテーブル、子、親、およびGrandParentを持っています。子には親を指す列(parentId)があります(多対1の関係)。 Parentには、GrandParent(別の多対1)を指す列(grandParentId)があります。私がGrandParentとParentに挿入すると、両方とも動作します。ただし、子に挿入すると、「外部キー制約」違反で失敗します。2レベルの多対1の関係での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`))
親テーブルの親と祖父母の制約を削除すると、3番目のステートメントが機能します。
あなたのお役に立ちました!
私は5.5.10 MySQLでMacを稼働しています – Eric