MySQL 的锁应用实例

一、问题

create table `mchopin` (  
`id` bigint unsigned  not null auto_increment comment '主键', 
`code` varchar(64)  not null comment '用户CODE', 
`name` varchar(25)  not null comment '姓名', 
`age` int  not null comment '年龄', 
primary key (id), 
UNIQUE KEY `idx_code` (code),
key `idx_name` (name)) 
default charset=utf8 comment='用户表';

以下语句加了哪些锁:

update mchopin set age = 11 where id = 10;
update mchopin set age = 11 where code = 'xxxx';
update mchopin set age = 11 where name = 'jack';
update mchopin set age = 11 where age = 12;

Tips:考虑不同隔离级别下的聚簇索引和二级索引的加锁

二、加锁分析

1️⃣以下几个 case 中,数据库的隔离级别是 Read Committed(RC)

  1. 主键
    update mchopin set age = 11 where id = 10;对id=10的数据上加X锁

  2. 唯一索引
    update mchopin set age = 11 where code = 'xxxx';索引记录加X锁 && 对应行加X锁

  3. 非唯一索引
    update mchopin set age = 11 where name = 'jack';索引记录加X锁 && 对应行加X锁。与唯一索引比,这里可能会加多行的锁。

  4. 无索引
    update mchopin set age = 11 where age = 12;全表扫描,对全表数据行加锁。既不是表锁,也不是只对符合要求的行加锁。MySQL 中,如果一个条件无法通过索引快速过滤,那么存储引擎层面就会将所有记录加锁后返回,然后由 MySQL Server层进行过滤。

2️⃣以下几个 case 中,数据库的隔离级别是 Repeatable Read(RR)

  1. 主键
    update mchopin set age = 11 where id = 10;与 RC 的一致。

  2. 唯一索引
    update mchopin set age = 11 where code = 'xxxx';与 RC 的一致。

  3. 非唯一索引
    update mchopin set age = 11 where name = 'jack';与 RC 的相比,索引上增加了GAP锁。这也是 RR 能保证不出现幻读的关键。

  4. 无索引
    update mchopin set age = 11 where age = 10;每条记录加X锁,记录之间加 GAP 锁。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JFS_Study

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值