2011-03-10 57 views
2

我有一个新表,该表具有旧的旧表的外键约束。旧表中填充了大量数据,但是当我尝试将新行添加到引用旧表中的行的新表时,出现Cannot add or update a child row: a foreign key constraint fails错误。将行添加到具有外键约束的表[MySQL]

如何将行添加到引用旧表中的行的新表中?

编辑 这里有两个疑问我想:

mysql> select user_pk from users where username = 'test_user'; 
+---------+ 
| user_pk | 
+---------+ 
| 123766 | 
+---------+ 
1 row in set (0.00 sec) 

mysql> insert into uservisit (user_id) values (123766); 
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`test_database`.`uservisit`, CONSTRAINT `user_id_refs_user_pk_37c3999c` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_pk`)) 

难道我做错了什么?

+0

你确定你想插入新表中的值中存在旧桌子? – 2011-03-10 17:50:18

+0

看看这里的评论回答你的问题:http://stackoverflow.com/questions/1253459/mysql-error-1452-cannot-add-or-update-a-child-row-a-foreign-key-constraint-辉 – Raelshark 2011-03-10 17:50:20

回答

4

您可以临时禁止外键检查,像这样:

SET foreign_key_checks = 0; 
... 
do updates 
... 
SET foreign_key_checks = 1; 

最好确保你所有的更新后,一切都是为了外键明智不过。

0

当您插入新行时,使用外键添加到列中的值也必须存在于旧表的引用列中。

也许如果你通过一些查询和示例数据,它会更容易帮助。