如果你想刪除除了一個ID最大的一切,再下面是「概念」,你想做什麼:
delete from CustomerContacts
where CustomerContractsId <> (select max(CustomerContactId)
from CustomerContacts cc2
where cc2.ContactFirstName = CustomerContacts.ContactFirstName and
cc2.ContactLastName = CustomerContacts.ContactLastName and
cc2.CustomerId = CustomerContacts.CustomerId
);
儘管這是標準SQL,但某些數據庫的語法可能略有不同。
EDIT(基於評論):
下獲取ID時primary
是真實的,或者,如果沒有,那麼最大的ID:
delete from CustomerContacts
where CustomerContractsId <> (select coalesce(max(case when primary then CustomerContactId end), max(CustomerContactId))
from CustomerContacts cc2
where cc2.ContactFirstName = CustomerContacts.ContactFirstName and
cc2.ContactLastName = CustomerContacts.ContactLastName and
cc2.CustomerId = CustomerContacts.CustomerId
);
您如何識別「主」聯繫?你的SQL不提供任何提示。 –