简体   繁体   English

在具有外键约束的表中添加行[MySQL]

[英]Adding rows to table with foreign key constraint [MySQL]

I have a new table that has a foreign key constraint to an old, legacy table. 我有一个新表,该表具有对旧的旧表的外键约束。 The old table is populated with a great deal of data, but when I try to add a row to the new table that references a row in the old table, I get a Cannot add or update a child row: a foreign key constraint fails error. 旧表中填充了大量数据,但是当我尝试向新表中添加行以引用旧表中的行时,我得到了Cannot add or update a child row: a foreign key constraint fails错误。

How do I add rows to the new table that reference rows in the old table? 如何在新表中添加引用旧表中的行的行?

EDIT Here are two queries I tried: 编辑这是我尝试的两个查询:

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`))

Am I doing something wrong? 难道我做错了什么?

You can temporary disable foreign key checks like so: 您可以像这样暂时禁用外键检查:

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

Better make sure that after all your updates everything is in order foreign key-wise though. 最好确保在进行所有更新之后,一切都按外键顺序进行。

When you insert your new row, the value you put in the column with the foreign key must also exist in the referenced column in the old table. 当您插入新行时,使用外键放入列中的值也必须存在于旧表的引用列中。

Maybe if you past some queries and example data, it would be easier to help. 也许,如果您过去进行一些查询和示例数据,将更容易获得帮助。

If you are using a version of MySQL prior to 5.5.13 you may be running into this bug: 如果您使用的是5.5.13之前的MySQL版本,则可能会遇到以下错误:
MySQL 5.5 foreign key constraint fails when foreign key exists 存在外键时,MySQL 5.5外键约束失败

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM