我的表中有一些行需要根据重复的几列进行删除。
例如Col1,Col2,Col3,Col4
如果Col1,Col2和Col3是重复的,无论Col4中的值是多少,我都希望删除这些重复项。我该怎么做呢?
答案 0 :(得分:3)
您可以使用where
子句执行此操作:
delete from t
where (col1, col2, col3) in (select col1, col2, col3
from t
group by col1, col2, col3
having count(*) > 1
);
答案 1 :(得分:3)
按这些ID分组并检查是否有重复项。这样找到的重复项删除了记录。
delete from mytable
where (col1,col2,col3) in
(
select col1,col2,col3
from mytable
group by col1,col2,col3
having count(*) > 1
);
答案 2 :(得分:1)
如果另一行具有相同的col1,col2和col3并且col4值较低,则使用EXISTS
删除行。即保留一个col1,col2,col3行。
delete from tablename t1
where exists (select 1 from tablename t2
where t2.col1 = t1.col1
and t2.col2 = t1.col2
and t2.col3 = t1.col3
and t2.col4 < t1.col4)
要删除两个/所有行,请跳过col4条件,改为group by
:
delete from tablename t1
where exists (select 1 from tablename t2
where t2.col1 = t1.col1
and t2.col2 = t1.col2
and t2.col3 = t1.col3
group by t2.col1, t2.col2, t2.col3
having count(*) > 1)