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

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


Quite likely your sourcecodes_tags table contains sourcecode_id values that no longer exists in your sourcecodes table. You have to get rid of those first.

Here's a query that can find those IDs:

SELECT DISTINCT sourcecode_id FROM    sourcecodes_tags tags LEFT JOIN sourcecodes sc ON tags.sourcecode_id=sc.id WHERE sc.id IS NULL;


I had the same issue with my MySQL database but finally, I got a solution which worked for me.
Since in my table everything was fine from the mysql point of view(both tables should use InnoDB engine and the datatype of each column should be of the same type which takes part in foreign key constraint).
The only thing that I did was to disable the foreign key check and later on enabled it after performing the foreign key operation.
Steps that I took:

SET foreign_key_checks = 0;
alter table tblUsedDestination add constraint f_operatorId foreign key(iOperatorId) references tblOperators (iOperatorId); QueryOK, 8 rows affected (0.23 sec) Records: 8  Duplicates: 0  Warnings: 0
SET foreign_key_checks = 1;


Use NOT IN to find where constraints are constraining:

SELECT column FROM table WHERE column NOT IN (SELECT intended_foreign_key FROM another_table)

so, more specifically:

SELECT sourcecode_id FROM sourcecodes_tags WHERE sourcecode_id NOT IN (SELECT id FROM sourcecodes)

EDIT: IN and NOT IN operators are known to be much faster than the JOIN operators, as well as much easier to construct, and repeat.