繁体   English   中英

2对多对一关系的mysql外键冲突

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM