CREATE TEMPORARY TABLE all_dav_ids AS ( SELECT dav_id FROM ( SELECT a.dav_id, ROW_NUMBER() OVER(PARTITION BY a.version,a.nickname,a.fn,a.n,a.note,a.org,a.url,a.fburl,a.caladruri,a.caluri, b.type,b.box_no,b.unit_no,b.street_address,b.locality,b.region,b.postcode,b.country,b.property, c.type,c.email,c.property, d.type,d.tel,d.property ORDER BY a.dav_id ASC ) AS Row FROM addressbook_resource a LEFT JOIN addressbook_address_adr b ON a.dav_id=b.dav_id LEFT JOIN addressbook_address_email c ON a.dav_id=c.dav_id LEFT JOIN addressbook_address_tel d ON a.dav_id=d.dav_id ) dups WHERE dups.Row > 1 ORDER BY dav_id ); DELETE FROM caldav_data WHERE dav_id IN (SELECT dav_id FROM all_dav_ids); DELETE FROM addressbook_address_tel WHERE dav_id IN (SELECT dav_id FROM all_dav_ids); DELETE FROM addressbook_address_email WHERE dav_id IN (SELECT dav_id FROM all_dav_ids); DELETE FROM addressbook_address_adr WHERE dav_id IN (SELECT dav_id FROM all_dav_ids); DELETE FROM addressbook_resource WHERE dav_id IN (SELECT dav_id FROM all_dav_ids);