一、问题
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)
主键
update mchopin set age = 11 where id = 10;对id=10的数据上加X锁
唯一索引
update mchopin set age = 11 where code = 'xxxx';索引记录加X锁 && 对应行加X锁
非唯一索引
update mchopin set age = 11 where name = 'jack';索引记录加X锁 && 对应行加X锁。与唯一索引比,这里可能会加多行的锁。
无索引
update mchopin set age = 11 where age = 12;全表扫描,对全表数据行加锁。既不是表锁,也不是只对符合要求的行加锁。MySQL 中,如果一个条件无法通过索引快速过滤,那么存储引擎层面就会将所有记录加锁后返回,然后由 MySQL Server层进行过滤。
2️⃣以下几个 case 中,数据库的隔离级别是 Repeatable Read(RR)
主键
update mchopin set age = 11 where id = 10;与 RC 的一致。
唯一索引
update mchopin set age = 11 where code = 'xxxx';与 RC 的一致。
非唯一索引
update mchopin set age = 11 where name = 'jack';与 RC 的相比,索引上增加了 GAP 锁。这也是 RR 能保证不出现幻读的关键。
无索引
update mchopin set age = 11 where age = 10;每条记录加X锁,记录之间加 GAP 锁。