【问题标题】:mysql foreign key violation on 2 levels of many-to-one relationmysql外键违反2级多对一关系
【发布时间】:2017-12-19 01:15:54
【问题描述】:

我有 3 个表,一个 Child、一个 Parent 和一个 GrandParent。 Child 有一个列 (parentId) 指向 Parent(多对一关系)。 Parent 有一个列 (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`))

如果我删除父表中的父到祖父约束,则第三条语句有效。

感谢您的帮助!

【问题讨论】:

  • 我在 mac 上运行 5.5.10 MySQL Community Server

标签: mysql foreign-keys constraints many-to-one


【解决方案1】:

您的脚本是正确的,对我有用。但是,在插入之前,请检查 Parent 表的 AUTO_INCREMENT 选项。是“1”吗?

例如,运行SHOW CREATE TABLE Parent; 语句。

【讨论】:

  • 感谢您试用@Devart。 id 是 1。我将 mysql 服务器升级到最新的 5.5.22。现在可以了!看起来它可能只是早期版本的mysql中的一个错误。
猜你喜欢
  • 1970-01-01
  • 2014-10-16
  • 1970-01-01
  • 2015-02-14
  • 1970-01-01
  • 1970-01-01
  • 2011-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多