【问题标题】:How can I remove rows that are 100% duplicates in a PostgreSQL table without a primary key? [duplicate]如何在没有主键的 PostgreSQL 表中删除 100% 重复的行? [复制]
【发布时间】:2020-02-23 20:42:34
【问题描述】:

我有一个包含大量列的 PostgreSQL 表。该表没有主键,现在包含几行,这些行与另一行 100% 重复。

如何在不删除原始文件的情况下删除这些重复项?

我在related question 上找到了这个答案,但我必须拼出每个列名,这很容易出错。 如何避免对表结构一无所知?

示例:

给定

create table duplicated (
 id int,
 name text,
 description text
);

insert into duplicated
values (1, 'A', null), 
       (2, 'B', null),
       (2, 'B', null),
       (3, 'C', null), 
       (3, 'C', null), 
       (3, 'C', 'not a DUPE!');

删除后,应保留以下行:

(1, 'A', null) 
(2, 'B', null)
(3, 'C', null) 
(3, 'C', 'not a DUPE!')

【问题讨论】:

  • @a_horse_with_no_name:编辑了我的问题以解释与您提出的重复问题的区别:我找不到的一个方面是如何避免知道表结构。这使得它的答案在我的场景中不适用。

标签: postgresql duplicates sql-delete


【解决方案1】:

按照this answer 中的建议,使用system column ctid 来区分其他相同行的物理副本。

为避免为行拼出不存在的“键”,只需使用row constructor row(table),它会返回一个 包含select * from table返回的整行的行值:

DELETE FROM duplicated
USING (
      SELECT MIN(ctid) as ctid, row(duplicated) as row
        FROM duplicated 
        GROUP BY row(duplicated) HAVING COUNT(*) > 1
      ) uniqued
      WHERE row(duplicated) = uniqued.row
      AND duplicated.ctid <> uniqued.ctid;

你可以在这个DbFiddle试试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-14
    • 1970-01-01
    • 2013-04-01
    • 1970-01-01
    • 2010-11-02
    相关资源
    最近更新 更多