Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

唯一索引等值查询 TIP #191

Open
NOS-AE opened this issue Oct 24, 2023 · 0 comments
Open

唯一索引等值查询 TIP #191

NOS-AE opened this issue Oct 24, 2023 · 0 comments

Comments

@NOS-AE
Copy link

NOS-AE commented Oct 24, 2023

图解MySQL 锁篇 MySQL是怎么加锁的 唯一索引等值查询 TIP

感觉TIP中的这个说法是否不够全面:

如果是用二级索引(不管是不是非唯一索引,还是唯一索引)进行锁定读查询的时候,除了会对二级索引项加行级锁(如果是唯一索引的二级索引,加锁规则和主键索引的案例相同),而且还会对查询到的记录的主键索引项上加「记录锁」。

利用二级索引查询的时候,如果是S锁(select...lock in share mode),并且走覆盖索引的话,也就是不会回表,这样是不会给主键索引加锁的,只会给二级索引加锁。这样带来的问题是,可以利用主键索引更新记录,导致第二次再查询的时候造成幻读。

解决办法有两种,第一个是查询多一个非覆盖索引的列,避免覆盖索引优化。第二个就是使用X锁(select...for update),这样Innodb就会认为你可能要做更新操作,就会主动把主键索引也加锁。

参考:MySQL实战45讲

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant