How do I delete all the duplicate records in a MySQL table without temp tables

前端 未结 9 1227
北恋
北恋 2020-11-27 03:46

I\'ve seen a number of variations on this but nothing quite matches what I\'m trying to accomplish.

I have a table, TableA, which contain the answers gi

相关标签:
9条回答
  • 2020-11-27 04:28

    Add Unique Index on your table:

    ALTER IGNORE TABLE `TableA`   
    ADD UNIQUE INDEX (`member_id`, `quiz_num`, `question_num`, `answer_num`);
    

    Another way to do this would be:

    Add primary key in your table then you can easily remove duplicates from your table using the following query:

    DELETE FROM member  
    WHERE id IN (SELECT * 
                 FROM (SELECT id FROM member 
                       GROUP BY member_id, quiz_num, question_num, answer_num HAVING (COUNT(*) > 1)
                      ) AS A
                );
    
    0 讨论(0)
  • 2020-11-27 04:28

    An alternative way would be to create a new temporary table with same structure.

    CREATE TABLE temp_table AS SELECT * FROM original_table LIMIT 0
    

    Then create the primary key in the table.

    ALTER TABLE temp_table ADD PRIMARY KEY (primary-key-field)
    

    Finally copy all records from the original table while ignoring the duplicate records.

    INSERT IGNORE INTO temp_table AS SELECT * FROM original_table
    

    Now you can delete the original table and rename the new table.

    DROP TABLE original_table
    RENAME TABLE temp_table TO original_table
    
    0 讨论(0)
  • 2020-11-27 04:32

    Instead of drop table TableA, you could delete all registers (delete from TableA;) and then populate original table with registers coming from TableA_Verify (insert into TAbleA select * from TAbleA_Verify). In this way you won't lost all references to original table (indexes,... )

    CREATE TABLE TableA_Verify AS SELECT DISTINCT * FROM TableA;
    
    DELETE FROM TableA;
    
    INSERT INTO TableA SELECT * FROM TAbleA_Verify;
    
    DROP TABLE TableA_Verify;
    
    0 讨论(0)
提交回复
热议问题