mysql – Cannot add or update a child row: a foreign key constraint fails

mysql – Cannot add or update a child row: a foreign key constraint fails

Youre getting this error because youre trying to add/update a row to table2 that does not have a valid value for the UserID field based on the values currently stored in table1. If you post some more code I can help you diagnose the specific cause.

It means that youre trying to insert into table2 a UserID value that doesnt exist in table1.

mysql – Cannot add or update a child row: a foreign key constraint fails

A simple hack can be to disable foreign key checks before performing any operation on the table. Simply query

SET FOREIGN_KEY_CHECKS=0

This will disable foreign key matching against any other tables. After you are done with the table enable it again

SET FOREIGN_KEY_CHECKS=1

This works for me a lot of times.


Please note that you enter the DANGER ZONE when you do this. While there are certainly valid use cases, you should only do this when you are certain you understand the implications.

Leave a Reply

Your email address will not be published.