根据主键查找-锁加在主键上
如 begin;select * from tt_copy where id=4 for update;
加锁情况
index PRIMARY of table test.tt_copy trx id 1101588 lock_mode X locks rec but not gap
根据普通索引查找-锁加在普通索引和主键上
如 begin;select * from tt_copy force index(idx_a) where a=4 for update;
加锁情况
index idx_a of table test.tt_copy trx id 1101590 lock_mode X locks rec but not gap
index PRIMARY of table test.tt_copy trx id 1101590 lock_mode X locks rec but not gap
还有一种会加GAP锁:RR隔离级别下,对有唯一索引的表执行insert on duplicate update操作,除了会对新插入的记录加x not gap外,还会对相邻记录加x gap
如何去掉GAP锁?
change the transaction isolation level to READ COMMITTED or enable the innodb_locks_unsafe_for_binlog system variable (which is now deprecated)
什么时候加next-key lock?
By default, InnoDB operates in REPEATABLE READ transaction isolation level. In this case, InnoDB uses next-key locks for searches and index scans, which prevents phantom rows
Insert Intention Lock
An insert intention lock is a type of gap lock set by INSERT operations prior to(在...之前) row insertion.
总结
• 原则之一
要分析一个死锁,必须深入业务,了解整个事务的逻辑(闭门无法造车)
• 原则之二`
GAP锁很复杂,为了减少GAP锁,减少GAP导致的死锁,尽量选择Read Committed隔离级别(RC + row based binlog,基本上能够解决所有问题,无需使用Repeatable Read)