Finding duplicate values in a SQL table

后端 未结 30 4484
南旧
南旧 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:53

    If you want to delete the duplicates, here's a much simpler way to do it than having to find even/odd rows into a triple sub-select:

    SELECT id, name, email 
    FROM users u, users u2
    WHERE u.name = u2.name AND u.email = u2.email AND u.id > u2.id
    

    And so to delete:

    DELETE FROM users
    WHERE id IN (
        SELECT id/*, name, email*/
        FROM users u, users u2
        WHERE u.name = u2.name AND u.email = u2.email AND u.id > u2.id
    )
    

    Much more easier to read and understand IMHO

    Note: The only issue is that you have to execute the request until there is no rows deleted, since you delete only 1 of each duplicate each time

提交回复
热议问题