Search code examples
phpmysqlsqldelete-rowsql-delete

Delete double rows when columns have identical entries


I have a database table (test_table) with an auto-increment column (id) and I want to delete all double (or more) entries when 3 specific columns (A, B, C) have identical entries.

    id    column_A    column_B    column_C
------------------------------------------------
    1     ooo         aaa         uuu
    2     ooo         aaa         uuu
    3     ttt         ppp         uuu
    4     ooo         aaa         uuu
    5     iii         kkk         ccc

In this example, the rows with id 2 and 4 should be deleted after executing the DELETE query.

Regards.


Solution

  • DELETE FROM tbl
    WHERE `id` NOT IN ( SELECT * FROM (
                                    SELECT MIN(`id`) 
                                    FROM tbl
                                    GROUP BY `column_A`
                                           , `column_B`
                                           , `column_C` 
                                  ) x
                  )
    

    SQLFiddle