2012-03-28 119 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

相关问题