简体   繁体   English

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

[英]mysql foreign key violation on 2 levels of many-to-one relation

I have 3 tables, a Child, a Parent, and a GrandParent. 我有3张桌子,一个孩子,一个父母和一个GrandParent。 Child has a column (parentId) pointing to Parent (many-to-one relationship). 子级有一个指向父级(多对一关系)的列(parentId)。 Parent has a column (grandParentId) pointing to GrandParent (another many-to-one). 父级有一列(grandParentId)指向GrandParent(另一个多对一)。 When I insert to GrandParent and Parent, they both work. 当我插入GrandParent和Parent时,它们都可以工作。 However, when I insert to Child, it fails with a "foreign key constraint" violation. 但是,当我插入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

Both GrandParent and Parent rows are created with id=1. GrandParent和Parent行均以id = 1创建。 Last statement fails with the following error (t1 is a new database). 最后一条语句失败,并显示以下错误(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`))

If I remove the parent to grandparent constraint in the parent table, the 3rd statement works. 如果我删除父表中的父对祖父母约束,则第三条语句有效。

Your help appreciated! 感谢您的帮助!

Your script is correct, and works for me. 您的脚本是正确的,并且对我有用。 But, before the inserting, check the AUTO_INCREMENT option for the Parent table. 但是,在插入之前,请检查Parent表的AUTO_INCREMENT选项。 Is it '1'? 是“ 1”吗?

For example, run SHOW CREATE TABLE Parent; 例如,运行SHOW CREATE TABLE Parent; statement. 声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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