Home >Database >Mysql Tutorial >How to Resolve MySQL Error 1452: Foreign Key Constraint Fails?
Mysql Error 1452: Adding or Updating Child Row Fails Due to Foreign Key Constraint
When attempting to add a foreign key to the sourcecodes_tags table referencing the sourcecodes table, an error occurs: "Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails."
Understanding the Issue
This error typically indicates that the sourcecode_id values present in the sourcecodes_tags table do not exist as corresponding primary key values (id) in the sourcecodes table. MySQL enforces referential integrity, ensuring that foreign keys reference valid primary keys in the parent tables.
Resolving the Error
To resolve this error, it is necessary to identify and remove the orphan sourcecode_id values from the sourcecodes_tags table. Execute the following query to find the missing primary key values:
SELECT DISTINCT sourcecode_id FROM sourcecodes_tags tags LEFT JOIN sourcecodes sc ON tags.sourcecode_id=sc.id WHERE sc.id IS NULL;
This query will return a list of sourcecode_id values that are not present in the sourcecodes table. Once identified, these orphan values can be removed using the DELETE statement:
DELETE FROM sourcecodes_tags WHERE sourcecode_id IN (SELECT DISTINCT sourcecode_id FROM sourcecodes_tags tags LEFT JOIN sourcecodes sc ON tags.sourcecode_id=sc.id WHERE sc.id IS NULL);
After removing the orphan values, re-execute the ALTER TABLE statement to add the foreign key:
ALTER TABLE sourcecodes_tags ADD FOREIGN KEY (sourcecode_id) REFERENCES sourcecodes (id) ON DELETE CASCADE ON UPDATE CASCADE;
This should successfully create the foreign key constraint without any errors.
The above is the detailed content of How to Resolve MySQL Error 1452: Foreign Key Constraint Fails?. For more information, please follow other related articles on the PHP Chinese website!