如何清理千万条以上大表中的数据?
以MySQL为例,正常删除数据我们都用 delete,比如清理掉创建时间小于 2022-09-01 的数据:
delete from huge_table where created_at<'2022-09-01'
但这种方式在大表里都行不通,尤其开了多列索引,因为 delete 的开销都在重建索引上了。
这个时候需要换个思路:
1、先 clone 原表,然后写入符合条件的数据
create table huge_table_new like huge_table;
insert into huge_table_new select * from huge_table where created_at > '2022-09-01';
2、替换表名
rename table huge_table to huge_table_del, huge_table_new to huge_table;
3、删除 huge_table_del ,或可以保留一段时间再删
drop table huge_table_del;
本作品采用《CC 协议》,转载必须注明作者和本文链接
本帖由系统于 2年前 自动加精
方法留着备用,不过created_at = 2022-09-01的数据丢了
我迁移都不要了,直接导入数据 :smiley:
insert into huge_table_new select * from huge_table where created_at > '2022-09-01'; 如果有线上流量一直在往原来表里面写 这就卡死了吧
我这边千万级表都是一分钟删除500条 这样不会大致大批量的删除卡表
或者用mysqldump直接加where条件导出,然后在导入,删除原表。。