mysql資料庫如何去除重複數據

coldplay.xixi
發布: 2020-09-29 15:19:36
原創
6461 人瀏覽過

mysql資料庫移除重複資料的方法:1、查詢需要刪除的記錄,會保留一筆記錄;2、刪除重複記錄,只保留一筆記錄,程式碼為【delete a from test1 a, (.. .)as bid from test1 c 其中..】。

mysql資料庫如何去除重複數據

mysql資料庫移除重複資料的方法:

1、查詢需要刪除的記錄,會保留一筆記錄。

select a.id,a.subject,a.RECEIVER from test1 a left join (select c.subject,c.RECEIVER ,max(c.id) as bid from test1 c where status=0 GROUP BY RECEIVER,SUBJECT having count(1) >1) b on a.id< b.bid where a.subject=b.subject and a.RECEIVER = b.RECEIVER and a.id < b.bid
登入後複製

2、刪除重複記錄,只保留一筆記錄。注意,subject,RECEIVER 要索引,否則會很慢的。

delete a from test1 a, (select c.subject,c.RECEIVER ,max(c.id) as bid from test1 c where status=0 GROUP BY RECEIVER,SUBJECT having count(1) >1) b where a.subject=b.subject and a.RECEIVER = b.RECEIVER and a.id < b.bid;
登入後複製

3、查找表中多餘的重複記錄,重複記錄是根據單一欄位(peopleId)來判斷

select * from people where peopleId in (select peopleId from people group by peopleId having count(peopleId) > 1)
登入後複製

4、刪除表中多餘的重複記錄,重複記錄是根據單個欄位(peopleId)來判斷,只留有rowid最小的記錄

delete from people where peopleId in (select peopleId from people group by peopleId  having count(peopleId) > 1) and rowid not in (select min(rowid) from people group by peopleId having count(peopleId )>1)
登入後複製

5、刪除表中多餘的重複記錄(多個欄位),只留有rowid最小的記錄

delete from vitae a where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1) and rowid not in (select min(rowid) from vitae group by peopleId,seq having count(*)>1)
登入後複製

看來想偷懶使用一句指令完成這個事好像不太顯示,還是老老實實的分步處理吧,思路先建立複製一個臨時表,然後對比臨時表內的數據,刪除主表裡的數據

alter table tableName add autoID int auto_increment not null; 
 
create table tmp select min(autoID) as autoID from tableName group by Name,Address; 
 
create table tmp2 select tableName.* from tableName,tmp where tableName.autoID = tmp.autoID; 
 
drop table tableName; 
 
rename table tmp2 to tableName;
登入後複製

更多相關免費學習推薦:mysql教學(影片)

#

以上是mysql資料庫如何去除重複數據的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板