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

前端 未结 9 1336
北恋
北恋 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:24

    As noted in the comments, the query in Saharsh Shah's answer must be run multiple times if items are duplicated more than once.

    Here's a solution that doesn't delete any data, and keeps the data in the original table the entire time, allowing for duplicates to be deleted while keeping the table 'live':

    alter table tableA add column duplicate tinyint(1) not null default '0';
    
    update tableA set
    duplicate=if(@member_id=member_id
                 and @quiz_num=quiz_num
                 and @question_num=question_num
                 and @answer_num=answer_num,1,0),
    member_id=(@member_id:=member_id),
    quiz_num=(@quiz_num:=quiz_num),
    question_num=(@question_num:=question_num),
    answer_num=(@answer_num:=answer_num)
    order by member_id, quiz_num, question_num, answer_num;
    
    delete from tableA where duplicate=1;
    
    alter table tableA drop column duplicate;
    

    This basically checks to see if the current row is the same as the last row, and if it is, marks it as duplicate (the order statement ensures that duplicates will show up next to each other). Then you delete the duplicate records. I remove the duplicate column at the end to bring it back to its original state.

    It looks like alter table ignore also might go away soon: http://dev.mysql.com/worklog/task/?id=7395

提交回复
热议问题