答案 0 :(得分:1)
一种方法是使用exists:
DELETE t0
FROM Password_Department t0
WHERE EXISTS
(
SELECT 1
FROM Password_Department t1
WHERE t0.PasswordFK = t1.PasswordFK
AND t0.DepartmentFK = t1.DepartmentFK
AND t0.Id > t1.Id
)
如果您更喜欢行号方法 -
delete x
from (
select *,
rn = row_number() over (partition by DepartmentFK, PasswordFK order by Id)
from Password_Department
) x
where rn > 1
删除重复条目后,应在PasswordFK和DepartmentFK上添加唯一约束:
ALTER TABLE Password_Department
ADD Constraint UC_Password_Department UNIQUE (PasswordFK , DepartmentFK)