![](/img/trans.png)
[英]Can't create a Many-To-One relation with all-delete-orphan cascade. MySQL says a foreign key constraint fails when deleting the parent
[英]mysql foreign key violation on 2 levels of many-to-one relation
我有3張桌子,一個孩子,一個父母和一個GrandParent。 子級有一個指向父級(多對一關系)的列(parentId)。 父級有一列(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`))
如果我刪除父表中的父對祖父母約束,則第三條語句有效。
感謝您的幫助!
您的腳本是正確的,並且對我有用。 但是,在插入之前,請檢查Parent
表的AUTO_INCREMENT選項。 是“ 1”嗎?
例如,運行SHOW CREATE TABLE Parent;
聲明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.