How to find duplicate records in PostgreSQL

前端 未结 4 1427
长情又很酷
长情又很酷 2021-01-29 17:17

I have a PostgreSQL database table called \"user_links\" which currently allows the following duplicate fields:

year, user_id, sid, cid

The uni

4条回答
  •  野的像风
    2021-01-29 17:43

    In order to make it easier I assume that you wish to apply a unique constraint only for column year and the primary key is a column named id.

    In order to find duplicate values you should run,

    SELECT year, COUNT(id)
    FROM YOUR_TABLE
    GROUP BY year
    HAVING COUNT(id) > 1
    ORDER BY COUNT(id);
    

    Using the sql statement above you get a table which contains all the duplicate years in your table. In order to delete all the duplicates except of the the latest duplicate entry you should use the above sql statement.

    DELETE
    FROM YOUR_TABLE A USING YOUR_TABLE_AGAIN B
    WHERE A.year=B.year AND A.id

提交回复
热议问题