How to remove duplicates from table using SQL query

后端 未结 7 1622
遇见更好的自我
遇见更好的自我 2020-12-17 04:34

I have a table which is as follows:

emp_name   emp_address  sex  matial_status  
uuuu       eee          m    s
iiii       iii          f    s
uuuu       eee         


        
7条回答
  •  轮回少年
    2020-12-17 05:37

    I would create a new table with a unique index over the columns that you want to keep unique. Then do an insert from the old table into the new, ignoring the warnings about duplicated rows. Lastly, I would drop (or rename) the old table and replace it with the new table. In MySQL, this would look like

    CREATE TABLE tmp LIKE mytable;
    ALTER TABLE tmp ADD UNIQUE INDEX myindex (emp_name, emp_address, sex, marital_status);
    INSERT IGNORE INTO tmp SELECT * FROM mytable;
    DROP TABLE mytable;
    RENAME TABLE tmp TO mytable;
    

    Or something similar (this is totally untested).

提交回复
热议问题