PostgreSQL how to delete duplicated values

試著忘記壹切 提交于 2019-12-11 05:32:11

问题


I have a table in my Postgres database where I forgot to insert a unique index. because of that index that i have now duplicated values. How to remove the duplicated values? I want to add a unique index on the fields translationset_Id and key.


回答1:


It appears that you only want to delete records which are duplicate with regard to the translationset_id column. In this case, we can use Postgres' row number functionality to discern between duplicate rows, and then to delete those duplicates.

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:


I think you are asking for this:

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);




回答3:


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
             );


来源:https://stackoverflow.com/questions/40717426/postgresql-how-to-delete-duplicated-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!