文章内容

2022/7/4 18:33:47,作 者: 黄兵

MySQLdb._exceptions.IntegrityError: (1452, 'Cannot add or update a child row

今天在使用 SQLAlchemy 更新数据库的时候,出现了如下错误:

MySQLdb._exceptions.IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (`production`.`#sql-2af9f_25adcc`, CONSTRAINT `follows_ibfk_2` FOREIGN KEY (`followed_id`) REFERENCES `users` (`id`))')

出现问题的原因:

外键关系涉及一个包含中心数据值的父表,以及一个具有相同值的子表,它们指向其父表。FOREIGN KEY 子句在子表中指定。

如果父表中没有匹配的候选键值,它将拒绝任何尝试在子表中创建外键值的 INSERT 或 UPDATE 操作。

也就是说 follows 表中添加一行,但是 follows 表中不存在于 users 表中的匹配。

解决方案:

可以先在会话中禁用外键检查,SQL 代码如下:

SET FOREIGN_KEY_CHECKS=0;

之后再次执行具体的 SQL 语句,即可解决问题。


参考资料:

1、ERROR 1452: Cannot add or update a child row: a foreign key constraint fails


黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - MySQLdb._exceptions.IntegrityError: (1452, 'Cannot add or update a child row

分享到:

发表评论

评论列表