GitHub - aneasystone/mysql-deadlocks: 收集一些常见的 MySQL 死锁案例

MySQL 中,对一行记录加锁的基本单位是临键锁(记录锁+间隙锁), 扫描过程中扫描到的记录都会加锁

  • 对于索引的等值查询,如果查询条件是唯一索引(包括主键索引),那么临键锁会退化成记录锁
  • 对于索引的等值查询,如果值不存在,就会扫描到第一个不符合条件的记录值,转换为间隙锁

An image to describe post

唯一等值查询下,行锁的加锁逻辑

create table t (
    id int not null,
    age int,
    val int,
    
    primary key (id),
    key(age) -- 普通索引
)

insert into t (id, age) values (1,1,1),(5,5,5),(10,10,10),(15,15,15),(20,20,20)

An image to describe post

普通索引等值查询下,行锁的加锁逻辑

先加临键锁,再找到下一个不满足条件的值,加上间隙锁。同时主键索引的行加上记录锁

create table t (
    id int not null,
    age int,
    val int,
    
    primary key (id),
    key(age) -- 普通索引
)

insert into t (id, age) values (1,1,1),(5,5,5),(10,10,10),(15,15,15),(20,20,20)

An image to describe post