Finding duplicate values in a SQL table

后端 未结 30 3993
南旧
南旧 2020-11-21 13:18

It\'s easy to find duplicates with one field:

SELECT name, COUNT(email) 
FROM users
GROUP BY email
HAVING COUNT(email) > 1

So if we have

30条回答
  •  渐次进展
    2020-11-21 13:44

    This selects/deletes all duplicate records except one record from each group of duplicates. So, the delete leaves all unique records + one record from each group of the duplicates.

    Select duplicates:

    SELECT *
    FROM table
    WHERE
        id NOT IN (
            SELECT MIN(id)
            FROM table
            GROUP BY column1, column2
    );
    

    Delete duplicates:

    DELETE FROM table
    WHERE
        id NOT IN (
            SELECT MIN(id)
            FROM table
            GROUP BY column1, column2
    );
    

    Be aware of larger amounts of records, it can cause performance problems.

提交回复
热议问题