Delete Duplicate email addresses from Table in MYSQL

前端 未结 5 1266
深忆病人
深忆病人 2020-12-18 09:20

I have a table with columns for ID, firstname, lastname, address, email and so on.

Is there any way

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-18 09:42

    I don't know if this will work in MYSQL (I haven't used it)... but you should be able to do something like the following snippets.

    I'd suggest you run them in order to get a feel for if the right data is being selected. If it does work, then you probably want to create a constraint on the column.

    Get all of the duplicate e-mail addresses:

    SELECT 
        EMAILADDRESS, COUNT(1)
    FROM
        TABLE
    GROUP BY EMAILADDRESS
    HAVING COUNT(1) > 1
    

    Then determine the ID from that gives:

    SELECT
        ID
    FROM 
        TABLE
    WHERE 
        EMAILADDRESS IN (
            SELECT 
                EMAILADDRESS
            FROM
                TABLE
            GROUP BY EMAILADDRESS
            HAVING COUNT(1) > 1
        )
    

    Then finally, delete the rows, based on the above and other constraints:

    DELETE 
    FROM 
        TABLE
    WHERE
        ID IN (
            SELECT
                ID
            FROM 
                TABLE
            WHERE 
                EMAILADDRESS IN (
                    SELECT 
                        EMAILADDRESS
                    FROM
                        TABLE
                    GROUP BY EMAILADDRESS
                    HAVING COUNT(1) > 1
                )
        )  
        AND FIRSTNAME = 'Instant'
    

提交回复
热议问题