LOCK IN SHARE MODE locks entire table

牧云@^-^@ 提交于 2019-12-12 03:06:10

问题


Documentation:

SELECT ... LOCK IN SHARE MODE sets a shared mode lock on any rows that are read. Other sessions can read the rows, but cannot modify them until your transaction commits. If any of these rows were changed by another transaction that has not yet committed, your query waits until that transaction ends and then uses the latest values.

However, some experimentation suggests that it locks more than the rows that are read.

CREATE TABLE example (a int);
START TRANSACTION;
SELECT a FROM example WHERE a = 0 LOCK IN SHARE MODE;

And then on another connection

INSERT INTO example VALUES (1);

The later connection blocks on the lock.

It would seems that LOCK IN SHARE MODE locks more than "any rows that are read".

What exactly does LOCK IN SHARE MODE lock?


回答1:


Make sure you have an index on the a column. Otherwise, in order to evaluate WHERE a = 0, it has to read every row in the table, and it will then set a lock on each row as it reads it.

ALTER TABLE example ADD INDEX (a);


来源:https://stackoverflow.com/questions/37493222/lock-in-share-mode-locks-entire-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!