只记录了部分https://www.cnblogs.com/zejin2008/p/5262751.html这个博客讲的很明白
注意:gap间隙锁是不互斥的,对一个范围加了gap锁 其他事务还可以对这个范围加gap锁
案例1. 在开发中先查询没有就插入 存在就更新
以id为主键为例,目前还没有id=22的行 Session1: select * from t3 where id=22 for update; Empty set (0.00 sec) session2: select * from t3 where id=23 for update; Empty set (0.00 sec) Session1: insert into t3 values(22,'ac','a',now()); 锁等待中…… Session2: insert into t3 values(23,'bc','b',now()); ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction
死锁的原因:
对存在的行加锁(主键) mysql只有行锁
对不存在的行加锁,mysql会使用间隙锁
锁住的范围:
如果记录id为(11,12)
select id = 22 这时会锁住12到无穷大
如果记录id为(11,30)
select id = 22 这时会锁住11到30
解决方法:
insert into t3(xx,xx)on duplicate key update 'xx'='XX' 针对insert只会加行锁
案例2:
mysql> select * from t3 where id=9 for update; +----+--------+------+---------------------+ | id | course | name | ctime | +----+--------+------+---------------------+ | 9 | JX | f | 2016-03-01 11:36:30 | +----+--------+------+---------------------+ 1 row in set (0.00 sec) Session2: mysql> select * from t3 where id<20 for update; 锁等待中 Session1: mysql> insert into t3 values(7,'ae','a',now()); ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction
原因:
session1先锁住了id=9的记录
session2锁住了id1-8的记录就阻塞了,后面10-19就不加锁了
session1 继续插入id = 7 死锁了
解决方法:
避免这种业务写法