• MySQL 百万级/千万级表 全量更新


    业务需求:今天从生成测试环境迁移了一批百万级/千万级表的数据,领导要求将这批数据进行脱敏处理(将真实姓名 、电话、邮箱、身份证号等敏感信息进行替换)。迁移数据记录数如下(小于百万级的全量更新不是本文重点):

    表名表名含义行记录数
    base_house房屋表4201183
    base_license预售证表17653209
    base_contract网签合同1500579

    解决办法:

    第一种:使用Update 语句进行全表更新。

    结论:update 更新时间慢长,单表百万级数据更新少说几小时起步。这种方案放弃

    第二种:使用存储过程,进行批量更新。

    实战:

    1. create procedure batch_update_house()
    2. begin
    3. -- 定义变量
    4. declare i int default 1;
    5. -- 批次更新大小 10000
    6. declare pageSize int default 10000;
    7. declare j int default 1;
    8. -- 421 为房屋总记录 数/10000 向上取整
    9. while i < 421 do
    10. if i = 1 then
    11. -- 温馨提示:update 语句不能直接使用limit,必须使用子查询
    12. update base_house set real_name ="******", real_phone="136****0511" where id in(select id from (select id from base_house limit i, pageSize ) as temp);
    13. else
    14. set j = i * pageSize + 1;
    15. -- 温馨提示:update 语句不能直接使用limit,必须使用子查询
    16. update base_house set real_name ="******", real_phone="136****0511" where id in(select id from (select id from base_house limit j, pageSize ) as temp);
    17. end if;
    18. set i = i + 1;
    19. end while;
    20. end

    功能说明: batch_update_house 房屋全量更新存储过程

    结论:伴随limit 偏移量量增大,每次花费寻找起始位置行的时间会延长,但能够避免超长时间执行。(入选清洗方案)   

    第三种:使用中间表,通过大表关联中间表进行update,通过where 条件命中索引,可以提升批量更新寻找起始位置行的时间     

    第一步:设计房屋清洗中间表:base_middle_house,设计两个字段(id 主键 自增长、house_id 房屋关联主键,唯一主键)

    1. create table "base_middle_house" (
    2. `id` int(11) not null auto_increment comment '主键',
    3. `house_id` varchar(200) not null comment '房屋关联主键'
    4. primary key (`id`),
    5. unique key `unique_house_id` (`house_id`)
    6. ) engine=InnoDB auto_increment=1 default charset=utf8mb4

    第二步:创建批量更新存储过程

    1. create procedure batch_update_middle_house()
    2. begin
    3. -- 定义变量
    4. declare i int default 1;
    5. declare pageSize int default 100000;
    6. declare j int default 1;
    7. while i < 43 do
    8. if i = 1 then
    9. update base_house h, base_middle_house t set h.real_name ="******", h.real_phone="136****0511" where t.house_id = h.id and t.id >=1 amd t.id <=100000;
    10. else
    11. set j = (i -1) * pageSize + 1;
    12. update base_house h, base_middle_house t set h.real_name ="******", h.real_phone="136****0511" where t.house_id = h.id and t.id >=j amd t.id <= i*pageSize;
    13. end if;
    14. set i = i + 1;
    15. end while;
    16. end

    实战:执行batch_update_middle_house 存储过程,base_house 全表4201183 记录数在1小时10分钟内全部清洗完毕。

    结论:第三种方案针对第二种方案对于寻找起始行位置通过索引进行了优化,批量更新的时间也有明细的提示,达到单台服务器每分钟处理5000条记录数据。初步达到领导的要求。(清洗方案s首推) 

  • 相关阅读:
    c#遍历文件重命名
    定时任务之基础实现方式(分布式任务调度)
    elementUI el-collapse 自定义折叠面板icon 和 样式 或文字展开收起
    python爬虫中json数据与python数据相互转换
    进程的基本概念(操作系统)
    HTML+CSS(2)
    Uts阿里百川旗舰版插件UniApp-X
    SP1557 GSS2 - Can you answer these queries II【线段树】
    基于PHP学生成绩查询系统设计与实现 开题报告
    基于Gin+Vue的博客后台管理系统
  • 原文地址:https://blog.csdn.net/zhouzhiwengang/article/details/127794994