Here’s some more SQL scraps I had stored here somewhere, these will save you some time
Delete orphaned records from contacts_cstm:
SELECT * -- DELETE ChildTable
FROM contacts_cstm ChildTable
LEFT JOIN contacts ParentTable
ON ChildTable.id_c = ParentTable.id
WHERE ParentTable.id IS NULL
Delete orphaned records from securitygroups_records:
SELECT record_id, module, s.deleted, c.last_name, c.deleted -- DELETE
FROM securitygroups_records s
LEFT JOIN contacts c
ON s.record_id = c.id
WHERE c.id IS NULL
AND s.module='Contacts'
These are phrased as SELECTS, but if you delete the SELECT keyword and use the DELETE that is after “–” (which marks an SQL comment), you will delete rows.
*** --> USE CAREFULLY, AT YOUR OWN RISK, AND BACKUP ENTIRE DATABASE FIRST <-- ***