Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

21 | 为什么我只改一行的语句,锁这么多? #32

Open
git-zjx opened this issue Aug 7, 2019 · 0 comments
Open

21 | 为什么我只改一行的语句,锁这么多? #32

git-zjx opened this issue Aug 7, 2019 · 0 comments
Assignees
Labels
MySQL MySQL MySQL实战45讲 MySQL实战45讲笔记
Projects

Comments

@git-zjx
Copy link
Owner

git-zjx commented Aug 7, 2019

加锁规则

包含了两个“原则”、两个“优化”和一个“bug”

  • 原则 1:加锁的基本单位是 next-key lock。希望你还记得,next-key lock 是前开后闭区间。
  • 原则 2:查找过程中访问到的对象才会加锁。
  • 优化 1:索引上的等值查询,给唯一索引加锁的时候,next-key lock 退化为行锁。
  • 优化 2:索引上的等值查询,向右遍历时且最后一个值不满足等值条件的时候,next-key lock 退化为间隙锁。
  • 一个 bug:唯一索引上的范围查询会访问到不满足条件的第一个值为止。

注意事项

  • lock in share mode 只锁覆盖索引,执行 for update 时,系统会认为你接下来要更新数据,因此会顺便给主键索引上满足条件的行加上行锁
  • 锁是加在索引上的
  • 如果你要用 lock in share mode 来给行加读锁避免数据被更新的话,就必须得绕过覆盖索引的优化,在查询字段中加入索引中不存在的字段
  • 在删除数据的时候尽量加 limit。这样不仅可以控制删除数据的条数,让操作更安全,还可以减小加锁的范围
  • next-key lock 执行的时候,是要分成间隙锁和行锁两段来执行的
  • 读提交隔离级别下有一个优化,即:语句执行过程中加上的行锁,在语句执行完成后,就要把“不满足条件的行”上的行锁直接释放了,不需要等到事务提交
@git-zjx git-zjx added MySQL MySQL MySQL实战45讲 MySQL实战45讲笔记 labels Aug 7, 2019
@git-zjx git-zjx added this to MySQL实战45讲 in MySQL Sep 18, 2019
@git-zjx git-zjx self-assigned this Apr 2, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
MySQL MySQL MySQL实战45讲 MySQL实战45讲笔记
Projects
MySQL
MySQL实战45讲
Development

No branches or pull requests

1 participant