How to delete duplicate rows in SQL Server?

后端 未结 23 1867
长情又很酷
长情又很酷 2020-11-22 00:58

How can I delete duplicate rows where no unique row id exists?

My table is

col1  col2 col3 col4 col5 col6 col7
john  1          


        
23条回答
  •  眼角桃花
    2020-11-22 01:31

    There are two solutions in mysql:

    A) Delete duplicate rows using DELETE JOIN statement

    DELETE t1 FROM contacts t1
    INNER JOIN contacts t2 
    WHERE 
        t1.id < t2.id AND 
        t1.email = t2.email;
    

    This query references the contacts table twice, therefore, it uses the table alias t1 and t2.

    The output is:

    1 Query OK, 4 rows affected (0.10 sec)

    In case you want to delete duplicate rows and keep the lowest id, you can use the following statement:

    DELETE c1 FROM contacts c1
    INNER JOIN contacts c2 
    WHERE
        c1.id > c2.id AND 
        c1.email = c2.email;
    

       

    B) Delete duplicate rows using an intermediate table

    The following shows the steps for removing duplicate rows using an intermediate table:

        1. Create a new table with the structure the same as the original table that you want to delete duplicate rows.

        2. Insert distinct rows from the original table to the immediate table.

        3. Insert distinct rows from the original table to the immediate table.

     

    Step 1. Create a new table whose structure is the same as the original table:

    CREATE TABLE source_copy LIKE source;
    

    Step 2. Insert distinct rows from the original table to the new table:

    INSERT INTO source_copy
    SELECT * FROM source
    GROUP BY col; -- column that has duplicate values
    

    Step 3. drop the original table and rename the immediate table to the original one

    DROP TABLE source;
    ALTER TABLE source_copy RENAME TO source;
    

    Source: http://www.mysqltutorial.org/mysql-delete-duplicate-rows/

提交回复
热议问题