MySQL 1452 - 无法添加或更新子行:外键约束失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18965424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
1452 - Cannot add or update a child row: a foreign key constraint fails
提问by Mia Raunegger
I'm getting this error:
我收到此错误:
1452 - Cannot add or update a child row: a foreign key constraint fails.
1452 - 无法添加或更新子行:外键约束失败。
I've located them and try to get rid of the references with
我找到了它们并尝试删除参考文献
alter table tillh?r drop foreign key kat_id;
But getting this error instead:
但是却收到此错误:
#1025 - Error on rename of '.\recept\tillh@1ir' to '.\recept#sql2-1570-3cb' (errno: 152).
#1025 - 将 '.\recept\tillh@1ir' 重命名为 '.\recept#sql2-1570-3cb' 时出错(错误号:152)。
What do I do wrong?
我做错了什么?
回答by Mihai
Before you query run
在查询运行之前
SET FOREIGN_KEY_CHECKS=0
then set it to 1 after you`re done.
完成后将其设置为1。
回答by Jakir Hosen Khan
I face same problem. I solve this issue by clearing, i.e. deleting all data from child table and successfully done.
我面临同样的问题。我通过清除解决了这个问题,即从子表中删除所有数据并成功完成。
This is occur if child table contain some data with the foreign key that that are not in parent table i.e, if there are two table called Person(with column id, name, address) and order(with column id, person_id, order_name); order.person_id is foreign key of person.id and order table contain person_id that is not present in person table.
如果子表包含一些带有外键但不在父表中的数据,即,如果有两个名为Person(列 id、名称、地址)和order(列 id、person_id、order_name)的表,就会发生这种情况;order.person_id 是 person.id 的外键,order 表包含 person_id 中不存在的 person 表。
You can solve this using the following query
您可以使用以下查询解决此问题
Delete from order where person_id NOT IN (select id from person where person.id = order.person_id)
回答by Cymbals
When I had this problem, it was due to the fact that I forgot to specify NULLS allowed when creating the foreign key id fields. I changed it after the fact, but 0's were already in the value. It could not find 0 in the matching table, and then gave this error. The fix: update the zero values to nulls.
当我遇到这个问题时,是因为我在创建外键 id 字段时忘记指定允许的 NULLS。事后我更改了它,但 0 已经在值中。它在匹配表中找不到 0,然后给出了这个错误。解决方法:将零值更新为空值。
回答by derick
You have to set nulls to your from the parent to child tables Or set the same values eg Child table first nam=Derick Parent table name=Derick
您必须将空值设置为从父表到子表或设置相同的值,例如 Child table first nam=Derick Parent table name=Derick