Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DELETE all where MySQL foreign key constraint does not fail

I am trying to delete a few records but am getting the following error:

Cannot delete or update a parent row: a foreign key constraint fails

The thing is, the foreign key constraint is failing for only 1 or 2 of my 100 records I wish to delete. I wish to write a query which deletes these 98-99 records, skipping the 1 or 2 which failed, which I can later manually inspect and delete/modify. Not stopping because of some single problematic record, but continuing with the others, ignoring that.

Is there a neat way to do this ?

like image 366
Garfield Avatar asked Aug 08 '11 06:08

Garfield


People also ask

How do I drop all foreign key constraints in MySQL?

You can drop a foreign key constraint using the following ALTER TABLE syntax: ALTER TABLE tbl_name DROP FOREIGN KEY fk_symbol; If the FOREIGN KEY clause defined a CONSTRAINT name when you created the constraint, you can refer to that name to drop the foreign key constraint.

What if I delete a row containing a foreign key to another table?

Suppose there is a main table containing a primary key and there is another table which contains a foreign key to this main table. So if we delete the row of main table it will delete the child table also.


1 Answers

You have to LEFT JOIN the referencing table and add a condition saying that the row is missing in that table.

For example:

DELETE a FROM a
LEFT JOIN b ON b.a_id = a.id
WHERE b.a_id IS NULL;
like image 74
crishoj Avatar answered Oct 22 '22 21:10

crishoj