2012-03-28 115 views
-1

我有兩個表 - 用戶和語言與他們的主鍵'id'的外鍵鏈接。 我已經檢查過,表的類型是innoDB。我有delete-限制和更新cascade。插入失敗:無法添加或更新子行:外鍵約束失敗

此插入查詢,將其插入的語言表:(它可以是多行被添加作爲形式具有動態clickevent按鈕)

if(empty($_SESSION['user_id'])) { // user not logged in; redirect to somewhere else } 

$sql_insert = "INSERT into `language` 
(`native`,`other`,`other_list`,`other_read`, `other_spokint` 
,`other_spokprod`,`other_writ` ) 
VALUES 
('$native','$other','$other_list','$other_read','$other_spokint','$other_spokprod', 
'$other_writ') "; 

mysql_query($sql_insert,$link) or die("Insertion Failed:" . mysql_error());  
} 

這是完整的錯誤:

Insertion Failed:Cannot add or update a child row: a foreign key constraint fails 
(`members`.`language`, CONSTRAINT `language_ibfk_1` FOREIGN KEY (`id`) 
REFERENCES `users` (`id`)) 

任何幫助,將不勝感激!

爲表語言表結構:

CREATE TABLE IF NOT EXISTS `language` (
`id` bigint(20) NOT NULL AUTO_INCREMENT, 
`native` varchar(30) NOT NULL, 
`other` varchar(30) NOT NULL, 
`other_list` varchar(9) NOT NULL, 
`other_read` varchar(9) NOT NULL, 
`other_spokint` varchar(9) NOT NULL, 
`other_spokprod` varchar(9) NOT NULL, 
`other_writ` varchar(9) NOT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; 


RELATIONS FOR TABLE `language`: 
`id` 
`users` -> `id` 
+0

該錯誤消息說,有你的ID FILD外鍵的問題。您是否檢查過在用戶表中存在帶ID的用戶? – F21 2012-03-28 11:16:42

+1

如何將自動遞增的語言表字段「id」映射到用戶表的外鍵「id」字段? – neeraj 2012-03-28 11:18:50

+0

是的我正在努力如何鏈接表和主鍵使用什麼。什麼是最好的解決方案? – user1296762 2012-03-28 11:21:22

回答

0

你必須使用這樣的結構:

create table users (
    id int not null auto_increment, 
    <additional fields>, 

    primary key (id) 
) ENGINE=InnoDB; 


create table language(
    id int not null auto_increment, 
    user_id int not null, 
    <additional fields>, 

    primary key (id), 
    foreign key (user_id) references users(id) on delete restrict on update cascade 
) ENGINE=InnoDB; 
+0

我已經這樣做了,仍然出現錯誤:插入失敗:無法添加或更新子行:外鍵約束失敗('members'.'language',CONSTRAINT'language_ibfk_1' FOREIGN KEY('user_id')REFERENCES'用戶'('id')ON UPDATE CASCADE)' – user1296762 2012-03-28 12:12:40

+0

是不是因爲你沒有在你的插入中提供user_id?如果外鍵被定義爲'not null',則必須在插入時提供它 – 2012-03-28 12:16:42

+0

但是每個插入的用戶ID會不同? – user1296762 2012-03-28 12:19:59

相關問題