Delete duplicated records from a table without pk or id or unique columns in mysql

前端 未结 4 1537
北荒
北荒 2021-01-20 22:30

I need to delete all the duplicated records from one of my tables the problem is that there isn\'t any id or unique or key column so I can\'t make something like this:

相关标签:
4条回答
  • 2021-01-20 22:54

    its pretty simple just make a temporary table and drop the other table then recreate it

    CREATE TEMPORARY TABLE IF NOT EXISTS no_dupes AS 
    (SELECT * FROM test GROUP BY phone, address, name, cellphone);
    
    TRUNCATE table test;
    INSERT INTO test (phone, address, name, cellphone) 
    SELECT phone, address, name, cell FROM no_dupes;
    

    WORKING DEMO

    0 讨论(0)
  • 2021-01-20 22:55

    I'd use sub query. Something like:

    DELETE FROM table1
    WHERE EXISTS (
    SELECT field1 
    FROM table1 AS subTable1 
    WHERE table1.field1 = subTable1.field1 and table1.field2 = subTable1.field2)
    

    Haven't try this out though.

    0 讨论(0)
  • 2021-01-20 23:02

    there is always a PK per table but you can combine columns as an unique id, so it's possible use a full row as a unique id if you want to... but I don't recommend use a full row, you should search what are the most significant columns that you can use a PK, when you have done that, you can copy the data, if there is no problem the mysql won't copy the duplicate rows.

    sorry for my bad english

    0 讨论(0)
  • 2021-01-20 23:19

    Adding a unique index (with all the columns of the table) with ALTER IGNORE will get rid of the duplicates:

    ALTER IGNORE TABLE table_name
      ADD UNIQUE INDEX all_columns_uq
        (phone, address, name, cellphone) ;
    

    Tested in SQL-Fiddle.

    Note: In version 5.5 (due to a bug in the implementation of fast index creation), the above will work only if you provide this setting before the ALTER:

    SET SESSION old_alter_table=1 ;
    
    0 讨论(0)
提交回复
热议问题