MySql 千万级数据去重

主播没有落网 主播只是懒得写文章

前言

前情提要:博主在搞一些奇奇怪怪的东西,需要对千万级别数据进行去重。

常规的 GROUP BY 语句去重挂着跑了一天一夜都没跑完,遂放弃。研究了一会之后搞出来了个新方法。

操作

id

首先需要给表上一个 id 字段,方便后面去重。

1
2
3
4
alter table TABLE_NAME add column id int(11) not null first ;
SET @row_number = 0;
UPDATE TABLE_NAME
SET id = (@row_number := @row_number + 1);

为什么不用自增:innodb 自增字段表无法压缩,占用空间非常大。反正我也不需要自增 id,去重后就删了。

索引

然后给 id 和需要去重的字段加上索引(查重的时候会快很多)。
索引

临时表

temp_delete_code 用于存放要删除的 code 。字段 delete_code,类型根据你的索引类型来,也需要添加索引。
temp_keep_id 用于存放去重保留的 id。字段 keep_id int(11),需要添加索引。

插入数据

temp_delete_code 表中插入要删除的 code

1
insert into temp_delete_code (delete_code) SELECT code FROM `TABLE_NAME ` GROUP BY `code` HAVING count(code) > 1;

temp_keep_id 插入不能保留的id

1
2
insert into temp_keep_id (keep_id)
SELECT min(id) FROM `TABLE_NAME ` GROUP BY `code` HAVING count(code) > 1;

删除

1
delete fromTABLE_NAME WHERE `code` in (select delete_code from temp_delete_code) and id not in (select keep_id from temp_keep_id);

MySql 千万级数据去重

https://omn.cc/archives/79.html

作者

空指针

发布于

2024-10-01

更新于

2024-10-01

许可协议

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

评论

You forgot to set the shortname for Disqus. Please set it in _config.yml.
Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×