如何在线改变巨型表的数据结构?

如果有一张上亿数据量的表,如何修改它的表结构?
我们在工作中往往会遇到这样的问题,随着业务不断发展,会有需要改动表结构,但当这张表的是一张巨型表时,修改表结构时非常痛苦的,直接线上DDL语句是个非常耗时的过程。会影响mysql系统性能,过程中会长时间阻塞用户服务,而且改动过程也会让程序员很慌张,那么如何改动表结构才是比较合理的呢?

DDL的执行过程

三个阶段:该过程是指alter table的一般流程
Phase 1: Initialization
In the initialization phase, the server determines how much concurrency is permitted during the operation, taking into account storage engine capabilities, operations specified in the statement, and user-specified ALGORITHM and LOCK options. During this phase, a shared upgradeable metadata lock is taken to protect the current table definition.

Phase 2: Execution
In this phase, the statement is prepared and executed. Whether the metadata lock is upgraded to exclusive depends on the factors assessed in the initialization phase. If an exclusive metadata lock is required, it is only taken briefly during statement preparation.

Phase 3: Commit Table Definition
In the commit table definition phase, the metadata lock is upgraded to exclusive to evict the old table definition and commit the new one. Once granted, the duration of the exclusive metadata lock is brief.






下面会讨论:
DDL语句获取的是什么锁?
获取锁的顺序?
如果DDL语句之前被其他事务获取了锁会发生什么?
如何才能解锁,让DDL语句继续执行?
在DDL语句等待过程中发生了事务会获取同样的锁,那会发生什么?如何解锁?

  1. 获取锁:MDL,metadata lock锁,该锁为mysql server端的树状等级锁。
    phase 1 中按顺序获取global的IX锁 ->schema的IX锁 -> table级别的Share_upgradable锁 -> 引擎级别的table的X锁。

    Share_Upgradable锁是在后面的过程中由该锁升级为其他锁,它是可升级的。
    在这里插入图片描述

  2. 若有其他事务已经持有了引擎级别table的X锁,DDL语句在这里的获取就会阻塞,直到阻塞超时或等待到table的metadata lock为止:

证明:
执行一下SQL语句,一切结果展示以performance_schema表数据为准。

session 1 session 2
begin;
select * from t_user1
alter table t_
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值