2012-03-26 15 views
0

私は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番目のステートメントが機能します。

あなたのお役に立ちました!

+0

私は5.5.10 MySQLでMacを稼働しています – Eric

答えて

0

あなたのスクリプトは正しいです、私のために働く。ただし、挿入する前に、ParentテーブルのAUTO_INCREMENTオプションを確認してください。それは '1'ですか?

たとえば、SHOW CREATE TABLE Parent;文を実行します。

+0

@Devartを試していただきありがとうございます。 IDは1です。私はmysqlサーバを最新の5.5.22にアップグレードしました。それは今働きます!以前のバージョンのmysqlのバグかもしれないようです。 – Eric

関連する問題