2012-03-26 82 views
0

我有3個表,一個Child,一個Parent和一個GrandParent。子項有一個指向Parent(多對一關係)的列(parentId)。 Parent有一個指向GrandParent(另一個多對一)的列(grandParentId)。當我插入GrandParent和Parent時,他們都工作。但是,當我插入到Child時,它會因「外鍵約束」違規而失敗。2級多對一關係的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`)) 

如果刪除父祖父母約束父表,第三個語句的工作。

您的幫助表示感謝!

+0

我在Mac上運行 – Eric 2012-03-26 06:35:15

回答

0

你的腳本是正確的,併爲我工作。但是,在插入之前,請檢查Parent表的AUTO_INCREMENT選項。是'1'嗎?

例如,運行SHOW CREATE TABLE Parent;聲明。

+0

5.5.10 MySQL社區服務器感謝您想出來@Devart。 ID是1.我升級了MySQL服務器到最新的5.5.22。它現在工作!它看起來可能只是早期版本的mysql中的一個錯誤。 – Eric 2012-03-26 14:31:33