If you have two tables, with already date on both of them, when you try to apply a foreign key to have referential integrity, you might get this error:
Cannot add or update a child row: a foreign key constraint fails ...
This means that you have one or more rows, in the referenced table, which is missing, so you are trying to reference a row that does not exist. You can use this SQL query to find the missing ids of the referenced table:
SELECT t1.id_referencing_t2
FROM a_table AS t1
LEFT JOIN referenced_table AS t2
ON t1.id_referencing_t2 = t2.primary_id_of_t2
WHERE t2.primary_id_of_t2 IS NULL
You have to substitute the following name with your real one:
id_referencing_t2: the id the reference the primary key on the referenced table.
primary_id_of_t2: the primary key of the referenced table.
a_table: the table that references the referenced table.
referenced_table: is the table that you want to reference, the table that have the missing ids.
The result of the query is the primary key of the rows that points to missing id in the other table. With those ids you can alter the value to a default one, or delete the rows.
Now you should be able to apply referencial integrity to your tables.
Labels: MySql, SQL