Home > Database > Mysql Tutorial > How to Resolve MySQL Error 1452: Foreign Key Constraint Fails?

How to Resolve MySQL Error 1452: Foreign Key Constraint Fails?

Susan Sarandon
Release: 2024-12-23 11:17:14
Original
731 people have browsed it

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;
Copy after login

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);
Copy after login

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;
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template