I have a table with already existing records, I want to add a Unique constraint on multiple columns(app_instance_config_uuid, external_resource_id and spaceId), but first, I need to remove already existing duplicates. This is an example of the table I want to add the constraint.
The best solution i found is
DELETE FROM spaces_apps
WHERE id IN ( SELECT id FROM ( SELECT MIN(id) AS id FROM spaces_apps
GROUP BY spaceId, app_instance_config_uuid, external_resource_id
HAVING COUNT(id) > 1 ) temp )
but the issue is that it only deletes one duplicate and if I need to delete more then one i need to run it again.
Important note that this is MySQL5.7 so using ROW_COUNT() and similar approaches doesn't work.
UPDATE: The first solution works even better when just changing IN to NOT IN and removing the HAVING clause! Thanks to @Pankaj for pointing this!
DELETE FROM spaces_apps
WHERE id IN ( SELECT id FROM ( SELECT MIN(id) AS id FROM spaces_apps
GROUP BY spaceId, app_instance_config_uuid, external_resource_id )temp )
