1、什么式gap鎖
(1)在索引記錄之間,或者在索引之前,或者索引之后的區間上加鎖,就是gap鎖。比如:
SELECT c1 FROM t WHERE c1 BETWEEN 10 and 20 FOR UPDATE;
由於在c1=10和c2=20之間已經加上gap鎖,所以不管數據表中是否有c1=15這條數據,這個sql都會阻止試圖插入c1=15的事務。
(2)一個gap鎖可能會鎖一個索引、多個索引、或者空索引。
(3)gap鎖權衡了性能和並發,並且它只用作於特定的隔離級別。
2、什么時候會出現gap間隙鎖
用唯一索引查詢唯一的行數據,並不會產生gap鎖。比如:
SELECT * FROM child WHERE id = 100;
如果id是唯一索引,就不會產生gap鎖;如果id不是索引或者id不是唯一索引,那么會產生gap鎖。
It is also worth noting here that conflicting locks can be held on a gap by different transactions. For example, transaction A can hold a shared gap lock (gap S-lock) on a gap while transaction B holds an exclusive gap lock (gap X-lock) on the same gap. The reason conflicting gap locks are allowed is that if a record is purged from an index, the gap locks held on the record by different transactions must be merged.
比如,事務A在間隙上擁有共享鎖,事務B在同樣的間隙上擁有排他鎖。