mysql 间隙锁专题
本文研究记录mysql间隙锁,涉及以下情况
唯一索引
非唯一索引
范围更新
等值更新
mysql8
mysql7
RR
RC
数据准备
mysql> select * from vodb.test1 limit 5; +----+------+------+--------+------------------------+---------------------+ | id | uid | tid | tname | tvalue | createtime | +----+------+------+--------+------------------------+---------------------+ | 1 | 1 | 0 | aaabbb | 有张有驰有分寸0 | 2021-04-20 14:06:44 | | 2 | 2 | 1 | aaabbb | 有张有驰有分寸1 | 2021-04-20 14:06:44 | | 8 | 8 | 1 | aaabbb | 有张有驰有分寸1 | 2021-04-20 14:14:25 | | 9 | 9 | 2 | aaabbb | 有张有驰有分寸2 | 2021-04-20 14:14:25 | | 10 | 10 | 3 | aaabbb | 有张有驰有分寸3 | 2021-04-20 14:14:25 | +----+------+------+--------+------------------------+---------------------+ 5 rows in set (0.00 sec)
表结构
mysql> desc vodb.test1; +------------+-------------+------+-----+-------------------+-------------------+ | Field | Type | Null | Key | Default | Extra | +------------+-------------+------+-----+-------------------+-------------------+ | id | int | NO | PRI | NULL | auto_increment | | uid | int | YES | UNI | NULL | | | tid | int | YES | MUL | NULL | | | tname | varchar(12) | YES | | NULL | | | tvalue | varchar(90) | YES | | NULL | | | createtime | datetime | YES | | CURRENT_TIMESTAMP | DEFAULT_GENERATED | +------------+-------------+------+-----+-------------------+-------------------+ 6 rows in set (0.00 sec)
mysql7、非唯一索引、范围更新、RR
mysql> begin; Query OK, 0 rows affected (0.00 sec) mysql> select * from test1 where tid between 1 and 7 for update;
mysql> insert into vodb.test1(id,uid,tid,tname,tvalue) values(4,4,1,'a','b');
结论:会锁定间隙,不允许其他事务插入
mysql7、非唯一索引、等值更新、RR
mysql> select * from test1 where tid =1 for update;
mysql> insert into vodb.test1(id,uid,tid,tname,tvalue) values(3,3,2,'a','b'); ^C^C -- query aborted ERROR 1317 (70100): Query execution was interrupted mysql> mysql> insert into vodb.test1(id,uid,tid,tname,tvalue) values(5,5,2,'a','b'); ^C^C -- query aborted ERROR 1317 (70100): Query execution was interrupted
结论:会锁定间隙,不允许其他事务插入
mysql7、唯一索引、范围更新、RR
mysql> select * from test1 where uid between 2 and 8 for update; +----+------+------+--------+------------------------+---------------------+ | id | uid | tid | tname | tvalue | createtime | +----+------+------+--------+------------------------+---------------------+ | 2 | 2 | 1 | aaabbb | 有张有驰有分寸1 | 2021-04-20 14:17:20 | | 8 | 8 | 7 | aaabbb | 有张有驰有分寸7 | 2021-04-20 14:17:20 | +----+------+------+--------+------------------------+---------------------+ 2 rows in set (0.00 sec)
mysql> insert into vodb.test1(id,uid,tid,tname,tvalue) values(3,3,2,'a','b'); ^C^C -- query aborted ERROR 1317 (70100): Query execution was interrupted
结论:会锁定间隙,不允许其他事务插入
mysql7、唯一索引、等值更新、RR :会锁定间隙,不允许其他事务插入
其他场景,mysql8 等,记录略,结果如下
---------------------------------------------------------------------------------------------------------------
RR 级别:不管是唯一索引还是非唯一索引,更新数据锁类型:行锁+间隙锁
RC 级别:不管是唯一索引还是非唯一索引,更新数据锁类型:行锁,无间隙锁
---------------------------------------------------------------------------------------------------------------