Home > Database > Mysql Tutorial > How to Resolve 'Foreign Key Constraint Fails' Errors in MySQL?

How to Resolve 'Foreign Key Constraint Fails' Errors in MySQL?

Patricia Arquette
Release: 2024-12-28 09:21:11
Original
272 people have browsed it

How to Resolve

Addressing the "Foreign Key Constraint Fails" Error in MySQL

When adding a foreign key to an existing table that references another, it's crucial to ensure that the referenced rows exist in the parent table. Otherwise, the "Cannot add or update a child row: a foreign key constraint fails" error can occur.

In the provided case, you are trying to add a foreign key (sourcecode_id) in the sourcecodes_tags table that references the sourcecodes table. However, based on your SHOW CREATE TABLE queries, it appears that there is no foreign key defined on the sourcecodes_tags table referencing the sourcecodes table.

The error message indicates that there is a foreign key violation, meaning that some sourcecode_id values in the sourcecodes_tags table do not exist in the sourcecodes table. To resolve this issue, you need to identify and remove those orphaned records.

Identifying Orphaned Records

To find the sourcecode_id values that do not exist in the sourcecodes table, you can use the following query:

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 the sourcecode_id values that are not associated with any rows in the sourcecodes table.

Removing Orphaned Records

Once you have identified the orphaned records, you can delete them using a 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 orphaned records, you should be able to add the foreign key constraint without any issues.

ALTER TABLE sourcecodes_tags 
ADD FOREIGN KEY (sourcecode_id) 
REFERENCES sourcecodes (id) 
ON DELETE CASCADE ON UPDATE CASCADE;
Copy after login

The above is the detailed content of How to Resolve 'Foreign Key Constraint Fails' Errors in MySQL?. 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