zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

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

2023-03-14 22:43:52 时间

Caused by: com.mysql.jdbc.exceptions.jdbc4.
MySQLIntegrityConstraintViolationException: 
Cannot add or update a child row: a foreign
 key constraint fails (`数据库`.`表名`, 
CONSTRAINT `FK_Reference_13` FOREIGN KEY (`user_id`) 
REFERENCES `user_info` (`id`))
at sun.reflect.GeneratedConstructorAccessor438.newInstance(Unknown Source)

译文:

image

报错的原因大概分为三种:


原因一:

      添加的外键列与另一个表的唯一索引列(一般是主键)的数据类型不同

原因二:
     要添加外键的表类型与另一个表的存储引擎是不是都为innodb引擎
     #查看表引擎
 方法1:

show create table 表名;

  方法2:

show table status from 数据库 where name=‘表名’;

方法3:

use information_schema;
select table_catalog,table_schema,table_name,engine from tables
where table_schema=‘数据库名’ and table_name=‘表名’;

原因三:
设置的外键与另一个表中的唯一索引列(一般是主键)中的值不匹配
#解决办法:删除要成为外键的列,再次创建并默认为NULL

原因四:

如果两个表的相关列已经有数据了,如果但是数据不匹配的话,要把不匹配的数据删除后才能添加外键成功

解决办法:把不匹配的数据删除