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?
views:
76answers:
1If the foreign key is ON DELETE CASCADE
, then deleting the duplicate rows will also delete the dependent rows, e.g., if you have a table customers
and a table orders
, and a foreign key like ALTER 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 has ON DELETE SET NULL
, then the orders will not be deleted, but their customer_id
values 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.