关于next-key锁,gap锁区间的疑问

表user结构如下:

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL DEFAULT '',
  `score` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `index_score` (`score`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

当前的user表数据如下:

id name score
1 test1 5
2 test2 10
3 test3 15
4 test4 22

我测试gap锁区间的sql如下:

事务隔离级别为RR
session 1 session 2
begin; begin;
update user set name = 'test' where score = 15; -
- insert into user values(5, 'test5', 10); # 阻塞
- insert into user values(5, 'test5', 21); # 阻塞
commit; -
- commit;
Suppose that an index contains the values 10, 11, 13, and 20. The possible next-key locks for this index cover the following intervals, where a round bracket denotes exclusion of the interval endpoint and a square bracket denotes inclusion of the endpoint:

(negative infinity, 10]
(10, 11]
(11, 13]
(13, 20]
(20, positive infinity)

14.6.4.2 InnoDB Record, Gap, and Next-Key Locks

按照上面的说明,gap锁的区间应该是(10, 15],(15, 22],也就是(10, 22],但是我实际测试发现gap锁区间为[10, 22)?

环境说明:

System: ubuntu 16.04
Mysql Version: 5.5.56
阅读 5.1k
3 个回答

最近也在看这一块,虽然知道晚了,万一以后有小伙伴有需要呢。。。
image.png

=.=.

事物分开,你是21的时候阻塞了。应该是锁(10,22)

begin;
-- 插入score value为10~21的时候会阻塞
insert into user values(5, 'test5', 10);

对于精准匹配来说,它的扫描区间是[15,15],它会对15进行加next-key,也就是(10,15],然后会对下一条记录22加gap锁(15,22)。

update user set name = 'test' where score = 15;
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题