2016-03-03 55 views
0

由於編程錯誤,我有重複的條目。SQL:刪除具有重複字段的行

表範例:

id | group | userNum | username | name 
--------------------------------------- 
1 | AA11 | D-01 | user1 | Donald 
2 | AA11 | D-02 | user2 | Cruz 
3 | AA11 | D-03 | user3 | Rubio 
4 | AA11 | D-01 | user1 | Donald <------DUPLICATE 
5 | AA11 | D-04 | user4 | Cruz 
6 | AA22 | D-03 | user2 | Rubio 
7 | AA22 | D-02 | user1 | Donald 

userNum,用戶名必須是唯一的每個組,但是一組可具有userNum,用戶名,名,其在其他組中發現。

+1

你正在使用哪個數據庫?有幾種不同的方法可以做到這一點。 – sgeddes

+0

我正在使用mysql – leakybytes

+1

可能的重複[如何刪除重複行?](http://stackoverflow.com/questions/18932/how-can-i-remove-duplicate-rows) – Emmet

回答

1

一個標準的SQL方法是WHERE子句中使用子查詢。例如:

delete from example 
    where id not in (select min(id) 
        from example e2 
        group by group, userNum, username, name 
        ); 

這在MySQL中不起作用。你可以使用類似的方法做left join

delete e 
    from example e left join 
     (select min(id) as minid 
      from example e2 
      group by group, userNum, username, name 
     ) ee 
     on e.id = ee.minid 
    where ee.minid is null; 
0

在您的查詢的末尾添加group by userNum, username, group ..