1. 程式人生 > >(轉)刪除表中重複資料sql語句

(轉)刪除表中重複資料sql語句

查詢表中重複資料 
select * from employee where employeeId in (select employeeId from employee group by employeeId having count(employeeId) > 1)

刪除表中多餘的重複記錄,重複記錄是根據單個欄位(employeeId)來判斷,只留有rowid最小的記錄 
delete from employee where employeeId in (select employeeId from employee group by employeeId having count(employeeId) > 1) 
and rowid not in (select min(rowid) from employee group by employeeId having count(employeeId )>1)

查詢表中多餘的重複記錄(多個欄位) 
select * from employee e 
where (e.employeeId,e.phoneNo) in (select employeeId,phoneNo from employee group by employeeId,phoneNo having count(*) > 1)

刪除表中多餘的重複記錄(多個欄位),只留有rowid最小的記錄 
delete from employee e 
where (e.employeeId, e.phoneNo) in (select employeeId, phoneNo from employee group by employeeId,phoneNo having count(*) > 1) 
and rowid not in (select min(rowid) from employee group by employeeId,phoneNo having count(*)>1)

查詢表中多餘的重複記錄(多個欄位),不包含rowid最小的記錄 
select * from employee e 
where (e.employeeId,e.phoneNo) in (select employeeId, phoneNo from employee group by employeeId,phoneNo having count(*) > 1) 
and rowid not in (select min(rowid) from employee group by employeeId,phoneNo having count(*)>1)

通用:

delete from table t 
where (t.欄位1, t.欄位2, … , t.欄位n) in (select 欄位1, 欄位2, … , 欄位n from table group by 欄位1, 欄位2, … , 欄位n having count(*) > 1)
and rowid not in (select min(rowid) from table group by 欄位1, 欄位2, … , 欄位n having count(*)>1)

此外:

如果只是查詢的時候, 不顯示重複, 只需select distinct 欄位 from table….
--------------------- 
作者:關耳木 
來源:CSDN 
原文:https://blog.csdn.net/germoo/article/details/79960480 
版權宣告:本文為博主原創文章,轉載請附上博文連結!