十年網(wǎng)站開發(fā)經(jīng)驗 + 多家企業(yè)客戶 + 靠譜的建站團隊
量身定制 + 運營維護+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
工作中,我們經(jīng)常有需要刪除一些重復數(shù)據(jù)的這種需求。重復數(shù)據(jù)可能是程序bug造成的
公司主營業(yè)務:網(wǎng)站設計制作、網(wǎng)站制作、移動網(wǎng)站開發(fā)等業(yè)務。幫助企業(yè)客戶真正實現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競爭能力。創(chuàng)新互聯(lián)是一支青春激揚、勤奮敬業(yè)、活力青春激揚、勤奮敬業(yè)、活力澎湃、和諧高效的團隊。公司秉承以“開放、自由、嚴謹、自律”為核心的企業(yè)文化,感謝他們對我們的高要求,感謝他們從不同領域給我們帶來的挑戰(zhàn),讓我們激情的團隊有機會用頭腦與智慧不斷的給客戶帶來驚喜。創(chuàng)新互聯(lián)推出滎陽免費做網(wǎng)站回饋大家。
好,讓我們看看如何刪除這些重復數(shù)據(jù)
刪除重復數(shù)據(jù)的思路呢,是這樣的,查看根據(jù)這個重復字段分組后的結果有沒有大于1的情況
如果有大于的1的情況呢,那就說明是有重復數(shù)據(jù)的!
1) 創(chuàng)建數(shù)據(jù)庫
create database ceshi;2) 創(chuàng)建表
CREATE TABLE t1 (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
name varchar(20) not null,
createdAt timestamp NOT NULL DEFAULT current_timestamp(),
updatedAt timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;3) 插入數(shù)據(jù)insert into t1 values(null,'haha',now(),now()),(null,'haha',now(),now()),(null,'xixi',now(),now()),(null,'heihei',now(),now()),(null,'hoho',now(),now()),(null,'hoho',now(),now()),(null,'sasa',now(),now()),(null,'haha',now(),now()),(null,'sasa',now(),now()),(null,'xixi',now(),now());
4) 查看數(shù)據(jù)select * from t1;

5) 根據(jù)最小id,重復字段name分組,假設我們的需求就是最后要保留第最小id的這些數(shù)據(jù),把其它重復的刪除
select min(id),name from t1 group by name having count(name)>1 order by id;
6) 使用別名關聯(lián)一下,這些數(shù)據(jù)就是重復的,最后要刪除的
select a.* from t1 a,(select *,min(id) from t1 group by name having count(name)>1)as b where a.name=b.name and a.id>b.id;

7) 記得先備份一下數(shù)據(jù)
create table bak_t1_20190621 like t1;
insert into bak_t1_20190621 select * from t1;
8) 刪除數(shù)據(jù)
delete a from t1 a,(select *,min(id) from t1 group by name having count(name)>1)as b where a.name=b.name and a.id>b.id;
9) 最后檢查一下,確實已經(jīng)沒有重復數(shù)據(jù)了
