9

MySQL 创建外键 报错 1452 - Cannot add or update a child row: a foreign

 3 years ago
source link: https://segmentfault.com/a/1190000039682286
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

大致报错内容

1452 - Cannot add or update a child row: a foreign key constraint fails

image.png

navicat创建外键时报错

关于navicat创建外键具体步骤,参见此文:navicat 数据表添加外键

两张表的数据不匹配(参见下图)


例子:
myorder表中userId字段是外键,关联user表中的userId字段。

myorder表中userId字段的值是0,而user表中没有userId=0的,这样就出现了数据不匹配的问题。如果ctrl+s保存myorder表就会报错。

image.png

image.png

image.png

修改myorder表中字段userId的值即可(与user表匹配)

ctrl+s,不再报错
image.png

Mysql错误1452 - Cannot add or update a child row: a foreign key constraint fails 原因及解决方法


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK