Delete duplicate records without creating a temporary table

后端 未结 5 2121
梦如初夏
梦如初夏 2020-12-12 01:12

I have a table with many duplicate records:

shop
ID     tax_id
1      10
1      10
1      11
2      10
2      12
2      10
2      10

I want

5条回答
  •  孤城傲影
    2020-12-12 01:55

    Working solution.

    //Sql query to find duplicates
    SELECT id, tax_id, count(*) - 1 AS cnt 
      FROM shop 
      GROUP BY id
      HAVING cnt > 1
    
    --- res
    
    +------+--------+-----+
    | id   | tax_id | cnt |
    +------+--------+-----+
    |    1 |     10 |   2 |
    |    2 |     10 |   3 |
    +------+--------+-----+
    
    
    //Iterate through results with your language of choice
    DELETE 
      FROM shop 
      WHERE id= 
        AND tax_id= 
      LIMIT 
    
    ---res (iterated)
    
    +------+--------+
    | id   | tax_id |
    +------+--------+
    |    1 |     10 |
    |    1 |     11 |
    |    2 |     12 |
    |    2 |     10 |
    +------+--------+
    

    The two queries will require a small piece of php in order to carry out the deletes

    $res = mysql_query("SELECT id, tax_id, count(*) - 1 AS cnt 
                          FROM shop 
                          GROUP BY id
                          HAVING cnt > 1")
    while($row = mysql_fetch_assoc($res)){
        mysql_query("DELETE 
                       FROM shop 
                       WHERE id=".$row['id']."
                           AND tax_id=". $row['tax_id']."
                       LIMIT ".$row['cnt'] -1 . ");
    }
    

    Edit: Revisited this recently, for what it's worth, here's an alternative solution using a temporary column, removing the need for a scripting language.

    ALTER TABLE shop ADD COLUMN place INT;
    
    SET @i = 1
    
    UPDATE shop SET place = @i:= @i + 1;
    
    DELETE FROM shop WHERE place NOT IN (SELECT place FROM items GROUP BY id, tax_id);
    
    ALTER TABLE shop DROP COLUMN place;
    

提交回复
热议问题