相当晚但最简单的解决方案可能如下假设我们有表emp_dept(empid,deptid),其中有重复的行,这里我使用@Count 作为变量.. 例如允许2 个重复然后@count = 2 在Oracle 数据库上
delete from emp_dept where @Count <= ( select count(1) from emp_dept i where i.empid = emp_dept.empid and i.deptid = emp_dept.deptid and i.rowid < emp_dept.rowid )
在 sql server 或任何不支持 row id kinda 特性的数据库上,我们需要添加标识列来标识每一行。假设我们已将 nid 作为身份添加到表中
alter table emp_dept add nid int identity(1,1) -- to add identity column
现在删除重复的查询可以写成
delete from emp_dept where @@Count <= ( select count(1) from emp_dept i where i.empid = emp_dept.empid and i.deptid = emp_dept.deptid and i.nid< emp_dept.nid )
这里的概念是删除所有存在其他行的行,这些行具有相似的核心值但 n 或更多数量的较小 rowid 或标识。因此,如果存在重复行,那么具有较高行 ID 或标识的行将被删除。并且对于没有重复的行,它无法找到较低的行ID,因此不会被删除。