SQL duplicates with different primary keys

前端 未结 7 1336
青春惊慌失措
青春惊慌失措 2021-01-24 19:56

I have a table in this form:

id | firstname | lastname
---+-----------+----------
1  | alex      | marti
2  | mark      | finger
3  | alex      | marti
4  | ted          


        
7条回答
  •  闹比i
    闹比i (楼主)
    2021-01-24 20:34

    I ran into the same problem and this is what I did to resolve it. First I identified the dups with the following query:

     SELECT COUNT(*) as num, ID, Firstname, Lastname FROM TableA GROUP BY ID, Firstname, Lastname;
    

    Then I created a temp table. called TempTableA Which had the same columns as TableA and extra Column called Dups, you will see why further.

    then I did the following insert:

    INSERT INTO TempTableA(Dups, ID, Firstname, Lastname) SELECT COUNT(*) as num, ID, Firstname, Lastname FROM TableA GROUP BY ID, Firstname, Lastname having count(*)>=1;
    

    By now you might know why we added an extra column called dups. anywho..

    After that I did the following delete statement:

    DELETE FROM TableA Where ID NOT IN (SELECT t.ID  FROM TempTableA t);
    

    And presto that did the work for me remove the rest of the dups.

    Its not a one step process but it did do the job right.

    NOTE: you need to change the tableA to the correct name that you have as well as the column names in order for it to work. Let me know if you run into any issues.

提交回复
热议问题