简体   繁体   English

Next-key lock explication - 范围的主键

[英]Next-key lock explication - Primary key for range

I have the following query, and I wanted to use the diagram to CONFIRM IF I UNDERSTAND IT RIGHT:我有以下查询,我想使用图表来确认我是否理解正确:

SELECT * FROM table WHERE pk > 99;

"pk" is the primary key “pk”是主键

在此处输入图像描述

I am having trouble understanding the next key lock, I found this diagram to know which gap lock will be applied and which "next key locks".我无法理解下一个键锁,我发现这张图知道将应用哪个间隙锁以及哪个“下一个键锁”。

If the diagram is WRONG, let me know.如果图表有误,请告诉我。

The diagram look right.该图看起来正确。

I'll assume pk in your example is the primary key of an InnoDB table, and is therefore the clustered index.我假设您的示例中的pk是 InnoDB 表的主键,因此是聚簇索引。

The gap is locked starting one value greater than 97, and extending to infinity.间隙从大于 97 的一个值开始锁定,并扩展到无穷大。

It seems strange, because the values 98 and 99 may seem like they should be free of locks, because the condition is on WHERE pk > 99 , and therefore does not match the values 98 or 99. But the next-key lock locks the whole gap before the index record, down to but not including the preceding index record.这看起来很奇怪,因为值 98 和 99 看起来应该没有锁,因为条件是WHERE pk > 99 ,因此与值 98 或 99 不匹配。但是下一个键锁锁定了整个索引记录之前的间隙,向下但不包括前面的索引记录。

https://dev.mysql.com/doc/refman/8.0/en/innodb-locking.html#innodb-next-key-locks says: https://dev.mysql.com/doc/refman/8.0/en/innodb-locking.html#innodb-next-key-locks说:

A next-key lock on an index record also affects the “gap” before that index record.索引记录上的下一个键锁也会影响该索引记录之前的“间隙”。 That is, a next-key lock is an index-record lock plus a gap lock on the gap preceding the index record.也就是说,下一个键锁是索引记录锁加上索引记录之前的间隙上的间隙锁。

Demo: In a first window, I start a transaction that acquires a next-key lock:演示:在第一个 window 中,我启动了一个获取下一键锁的事务:

mysql> select * from mytable;
+-----+-------+
| pk  | name  |
+-----+-------+
|   3 | hello |
|  97 | hi    |
| 101 | hola  |
| 103 | yo    |
| 107 | hey   |
+-----+-------+

mysql> start transaction;

mysql> select * from mytable where pk > 99 for update;
+-----+------+
| pk  | name |
+-----+------+
| 101 | hola |
| 103 | yo   |
| 107 | hey  |
+-----+------+

Now the index record for pk 101 is locked, as well as the gap following pk 97.现在 pk 101 的索引记录以及 pk 97 之后的间隙被锁定。

In a second window I test this:在第二个 window 中,我测试了这个:

mysql> insert into mytable values (99, 'test');
(hangs)

mysql> insert into mytable values (98, 'test');
(hangs)

mysql> update mytable set name='test' where pk=97;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM