Deleting duplicate record from table - SQL query

前端 未结 7 1055
有刺的猬
有刺的猬 2021-02-03 15:09

I need to delete duplicate rows only from the table, like I have 3 duplicate rows in the table, my query will delete 2 rows from 3 duplicated rows.

How can I get this? P

7条回答
  •  北荒
    北荒 (楼主)
    2021-02-03 15:29

    DELETE FROM `mytbl`
        INNER JOIN (
            SELECT 1 FROM `mytbl`
            GROUP BY `duplicated_column` HAVING COUNT(*)=2
        ) USING(`id`)
    

    Edit:

    My bad, the above query won't work.

    Assuming table structure:

    id int auto_increment

    num int # <-- this is the column with duplicated values

    The following query would work in MySQL (i checked):

    DELETE `mytbl` FROM `mytbl` 
        INNER JOIN 
        (
            SELECT `num` FROM `mytbl`
            GROUP BY `num` HAVING COUNT(*)=2
        ) AS `tmp` USING (`num`)
    

    The query would delete the rows that have 2 (not more or else) duplicated values in the num column.

    Edit (again):

    I suggest to add a key on the num column.

    Edit(#3):

    In case that the author wanted to delete the duplicated rows, the following should work for MySQL (it worked for me):

    DELETE `delete_duplicated_rows` FROM `delete_duplicated_rows`
        NATURAL JOIN (
            SELECT *
            FROM `delete_duplicated_rows`
            GROUP BY `num1` HAVING COUNT(*)=2
        ) AS `der`
    

    While assuming table structure is:

    CREATE TABLE `delete_duplicated_rows` (
      `num1` tinyint(4) DEFAULT NOT NULL,
      `num2` tinyint(4) DEFAULT NOT NULL
    ) ENGINE=MyISAM;
    

提交回复
热议问题