DELETE all where MySQL foreign key constraint does not fail

て烟熏妆下的殇ゞ 提交于 2020-01-12 14:02:31

问题


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 ?


回答1:


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;



回答2:


Use ignore:

DELETE IGNORE ...

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



来源:https://stackoverflow.com/questions/6978304/delete-all-where-mysql-foreign-key-constraint-does-not-fail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!