首页 > 解决方案 > 从 PostgreSQL 中删除重复项

问题描述

我正在使用以下内容queryPostgreSQL 10查找重复条目:

select
  column1, column2, count(*)
from mytable
  where column3 in ('yes', 'no')
group by column1, column2 having count(*) > 2;

是否可以PostgreSQL删除重复项,当然每个条目的第一个除外?

标签: sqlpostgresqlpostgresql-10

解决方案


假设您的表有一个主键:

delete from mytable t
    where t.pk <> (select min(t2.pk)
                   from mytable t2
                   where t2.column1 = t.column1 and
                         t2.column2 = t.column2 and
                         t2.column3 in ('yes', 'no')
                  );

推荐阅读