How to delete records in the table which are repeated?

前端 未结 6 1769
长情又很酷
长情又很酷 2021-01-25 03:35

Hi Here i came across a situation in which by mistakenly Without dropping the table i have run the batch file of the table which consists of some insert statements in detail

相关标签:
6条回答
  • 2021-01-25 04:04

    First , consider setting your ID fields as AI (auto increasment) and even PK (Primary Key).

    In order to remove those duplicated rows , we will create a new table and will move all those duplicated rows to it. After that , drop that table.

    CREATE TEMPORARY TABLE bad_temp AS SELECT DISTINCT * FROM alert_priority

    0 讨论(0)
  • 2021-01-25 04:09

    you can copy all unique records into a new table, then delete the old table:

    SELECT DISTINCT * INTO new_table FROM old_table
    
    0 讨论(0)
  • 2021-01-25 04:11
    CREATE TABLE new_tbl(id int AUTO_INCREMENT,priority_name);
    
    INSERT INTO new_tbl
    select priority_name from old_tbl group by priority_name;
    
    0 讨论(0)
  • 2021-01-25 04:12

    To just delete the duplicate new rows and leave the old ones in place (on the basis that I assume there are already other tables whose rows refer to the original rows):-

    DELETE FROM alert_priority
    WHERE Id IN (SELECT MaxId
    FROM (SELECT priority_name, MAX(Id) AS MaxId, COUNT(Id)  AS CountId
    FROM alert_priority
    GROUP BY priority_name
    HAVING CountId > 1))
    
    0 讨论(0)
  • 2021-01-25 04:15

    Following query will give you all records that you want to keep:

    SELECT min(id)
    FROM alert_priority
    GROUP BY priority_name
    HAVING count(*) > 1
        OR min(id) = max(id)
    

    To remove all duplicates, run this query:

    DELETE FROM alert_priority
    WHERE id NOT IN (
        SELECT min(id)
        FROM alert_priority
        GROUP BY priority_name
        HAVING count(*) > 1
            OR min(id) = max(id)
    )
    
    0 讨论(0)
  • 2021-01-25 04:20

    In SQL-Server it would be easy using ROW_NUMBER, but alas MySQL doesn't have a function like that :-(

    Best way to solve it would be as follows:

    • Create a new table identical in structure to the first, but with no data.
    • Use the query: INSERT INTO name_of_new_table SELECT DISTINCT * FROM name_of_old_table
    • Drop the old table
    • Rename the new table to whatever the old table was called.
    0 讨论(0)
提交回复
热议问题