mysql去重之實戰總結


一、有主鍵去重

a、單字段重復
 
table  ab
查詢重復記錄(一條)
select aid from ab group by aid having count(*)>1
result:
  查詢重復記錄(全部)
select * from ab t where t.aid in(select aid from ab group by aid having count(*)>1);
result:
   刪除重復記錄保留一條
delete from ab where aid in(
  select aid from ab group by aid having count(*)>1
)and id not in(
  select max(id)as id from ab group by aid having count(*)>1
)

剛開始想到這個sql,結果

 於是經過查資料,sql整改
delete from ab where aid in(
    select t.aid from(
        select aid from ab group by aid having count(*)>1
    ) t
)and id not in(
    select t.id from(
        select max(id) as id from ab group by aid having count(*)>1
    ) t
)        
 
 去重成功!
 
  b、多字段重復
table  ab
 查詢重復記錄(一條)
select aid,bid from ab group by aid,bid having count(*)>1
result:
   查詢重復記錄(全部)
select * from ab t where(t.aid,t.bid)in(select aid,bid from ab group by aid,bid having count(*)>1);
result:
 刪除重復記錄保留一條
delete from ab where (aid,bid) in (
	select t.aid,t.bid from (
		select aid,bid from ab group by aid,bid having count(*)>1
	) t
) and id not in (
	select t.id from (
		select max(id) as id from ab group by aid,bid having count(*)>1
	) t
)
去重成功!
 

二、無主鍵去重

單字段、多字段
table ab


  刪除重復記錄保留一條
--建臨時表插入去重數據
create table ab_temp (select * from ab group by aid,bid having count(*)>1);
--刪除重復數據
delete from ab where (aid,bid) in (
	select t.aid,t.bid from (
		select aid,bid from ab group by aid,bid having count(*)>1
	) t 
);
--插入去重數據
insert into ab select * from ab_temp;
--刪除臨時表
drop table ab_temp;
 去重成功!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM