How can I delete duplicate rows from a MySQL table when a foreign key relationship has already been setup up on those rows.
Can the duplicates be merged somehow and then foreign key updated with the new value?
How can I delete duplicate rows from a MySQL table when a foreign key
Share
If the foreign key is
ON DELETE CASCADE, then deleting the duplicate rows will also delete the dependent rows, e.g., if you have a tablecustomersand a tableorders, and a foreign key likeALTER TABLE orders ADD FOREIGN KEY customer_id REFERENCES customers (id) ON DELETE CASCADE, then deleting a customer will also delete that customer’s orders. Similarly, if the foreign key hasON DELETE SET NULL, then the orders will not be deleted, but theircustomer_idvalues will be set to NULL.If neither of these is the desired behaviour, craft a query that resolves the foreign key conflicts by altering the foreign key columns so that they reference the row you want to keep (i.e., update all orders to reference non-duplicate customers), then delete the offending rows.
Yet another alternative is to disable foreign key checks temporarily, but this will leave you with an inconsistent database, so I wouldn’t recommend this.