next-key locking

在centos7 mysql 5.7.27里, 默认的事务隔离级别是repeatable read, 默认使用next-key locking. 

我看到很多资料和文章都只解释了等值查询for update加X锁的情况, 那如果是大于或者大于等于查询呢?

以下是对next-key locking的一些理解, 我就不写太多概念的东西了, 难理解. 

create table n(a int, b varchar(10), c int, primary key(a), key(c));
insert into n select 1, '1', 1;
insert into n select 10, '10', 10;
insert into n select 20, '20', 20;
insert into n select 30, '30', 30;
insert into n select 50, '50', 50;

autocommit是连接级别的一个变量, 默认是打开的:

先把它关掉:

set @@autocommit=0;

 

如下语句会锁住[30, +无穷大):

select c from n where c>30 for update;

如下语句会锁住[20, 30]和[30, +无穷大), 其实就是[20, +无穷大):

select c from n where c>=30 for update;

其实是锁定前一个索引值到30之间, 以及30到+无穷大之间, 也包括30本身.

这些锁定都是在c索引上, c索引是建立在c列上的一个允许重复的普通索引.

以上.

猜你喜欢

转载自www.cnblogs.com/lihan829/p/11374613.html