DELETE all where MySQL foreign key constraint does not fail
Asked Answered
Y

2

14

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 ?

Yasmeen answered 8/8, 2011 at 6:6 Comment(0)
A
8

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;
Aboutface answered 15/1, 2013 at 17:28 Comment(0)
N
2

Use ignore:

DELETE IGNORE ...

http://dev.mysql.com/doc/refman/5.0/en/delete.html

Narine answered 8/8, 2011 at 6:8 Comment(2)
DELETE IGNORE doesn't achieve the goal. According to mysqlperformanceblog.com/2012/02/02/…, in 5.0, no rows are deleted in case of a FOREIGN KEY error, but in 5.1 and 5.5, rows up until the error occurs are deleted, and subsequent rows are left untouched.Aboutface
Neither did I, actually, until I noticed recently that my log purge cron job wasn't really doing its job :)Aboutface

© 2022 - 2024 — McMap. All rights reserved.