PostgreSQL如何删除重复值

时间:2016-11-21 10:01:21

标签: sql postgresql duplicates

我在Postgres数据库中有一个表,我忘了插入一个唯一索引。因为那个索引我现在有重复的值。如何删除重复的值?我想在字段translationset_Id和key上添加唯一索引。

enter image description here

4 个答案:

答案 0 :(得分:4)

我认为你要求这个:

DELETE FROM tablename WHERE id IN (SELECT id FROM (SELECT id, ROW_NUMBER() OVER (partition BY column1, column2, column3 ORDER BY id) AS rnum FROM tablename) t WHERE t.rnum > 1);

答案 1 :(得分:1)

您似乎只想删除与translationset_id列相关的重复记录。在这种情况下,我们可以使用Postgres'行号功能,用于辨别重复行,然后删除这些重复行。

WITH cte AS
(
    SELECT t.*, ROW_NUMBER() OVER (PARTITION BY translationset_id, key) AS rnum
    FROM yourTable t
)

DELETE FROM yourTable
WHERE translationset_id IN (SELECT translationset_id FROM cte WHERE rnum > 1)

答案 2 :(得分:0)

delete from mytable
where exists (select 1
              from mytable t2
              where t2.name = mytable.name and
                    t2.address = mytable.address and
                    t2.zip = mytable.zip and
                    t2.ctid > mytable.ctid
             );

答案 3 :(得分:0)

我认为最有效的方法如下。

  DELETE  FROM
    table_name a
    USING table_name b
  WHERE
      a.id < b.id and
      a.same_column = b.same_column;