我通常使用以下查询删除重复项:
delete from test a
using test b
where a.ctid < b.ctid
and a.col1=b.col1
and a.col2=b.col2
and a.col3=b.col3
此外,我见过人们使用以下查询:
DELETE FROM test WHERE test.ctid NOT IN
(SELECT ctid FROM (
SELECT DISTINCT ON (col1, col2) *
FROM test));
甚至这个(重复直到你用尽所有副本):
delete from test ju where ju.ctid in
(select ctid from (
select distinct on (col1, col2) * from test ou
where (select count(*) from test inr
where inr.col1= ou.col1 and inr.col2=ou.col2) > 1
我现在遇到了一个有500万行的表,其中列中有索引与where子句匹配。我想知道:
所有看起来一样的方法中,哪一种最有效,为什么?我刚刚运行了第二种方法,花了45分钟以上才删除重复项。我只是好奇哪种方法最有效,以防我需要从另一个巨大的表中删除重复项。它是否有一个主键并不重要,你可以随时创建或不创建。
ctid
值的比较速度相当慢,您是否有其他唯一标识行的方法?也许可以使用serial
(或identity
)列? - user330315