mysql資料去除重複及相關最佳化

來源:互聯網
上載者:User

標籤:style   blog   http   io   color   ar   sp   資料   div   

由於mysql不支援同時對一張表進行操作,即子查詢和要進行的操作不能是同一張表,因此需要通過暫存資料表中專以下。

1、單欄位重複

產生暫存資料表,其中uid是需要去重的欄位

create table tmp_uid as (select uid from user_info group by uid having count(uid))create table tmp_id as (select min(id) from user_info group by uid having count()uid)

數量量大時一定要為uid建立索引

alter table tmp_uid add index 索引名 (欄位名)alter table tmp_id add index 索引名 (欄位名)

刪除多餘的重複資料,保留重複資料中id最小的

delete from user_infowhere id not in (select id from tmp_id)and uid in (select uid from tmp_uid)

 

2、多欄位重複

如以上由於uid的重複間接導致了relationship中的記錄重複,所以繼續去重。

2.1 一般方法

基本的同上面:

產生暫存資料表

create table tmp_relation as (select source,target from relationship group by source,target having count(*)>1)create table tmp_relationship_id as (select min(id) as id from relationship group by source,target having count(*)>1)

建立索引

alter table tmp_relationship_id add index 索引名(欄位名)

刪除

delete from relationshipwhere id not in (select id from tmp_relationship_id)and (source,target) in (select source,target from relationship)

 

2.2 快速方法

實踐中發現上面的刪除欄位重複的方法,由於沒有辦法為多欄位重建索引,導致資料量大時效率極低,低到無法忍受。最後,受不了等了半天沒反應的狀況,本人決定,另闢蹊徑。

考慮到,估計同一記錄的重複次數比較低。一般為2,或3,重複次數比較集中。所以可以嘗試直接重複資料刪除項中最大的,直到刪除到不重複,這時其id自然也是當時重複的裡邊最小的。

大致流程如下:

(1)、選擇每個重複項中的id最大的一個記錄

create table tmp_relation_id2 as (select max(id) from relationship group by source,target having count(*)>1)

(2)、建立索引(僅需在第一次時執行)

alter table tmp_relation_id2 add index 索引名 (欄位名)

(3)、重複資料刪除項中id最大的記錄

delete from relationship where id in (select id from tmp_relation_id2)

(4)、刪除暫存資料表

drop table tmp_relation_id2

 

重複上述步驟(1),(2),(3),(4),直到建立的暫存資料表中不存在記錄就結束(對於重複次數的資料,比較高效)

 

本文章轉自 http://www.cnblogs.com/rainduck/archive/2013/05/15/3079868.html

mysql資料去除重複及相關最佳化(轉)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.