mysql innodb 行锁解锁后出现死锁
[Error] Deadlock found when trying to get lock; try restarting transaction
出现这个原因要记住一点就是:innodb的行锁 和解锁都是针对主键索引的。如果查询时根据索引锁表,但更新时却不是通过主键更新,那么等待的解锁查询的进程将会报1213错误,程序里有可能返回一个null值
实例:
table
soldgoods (表名)
soldgoodsID 索引
productid
businessid
开启线程A
执行:
set autocommit=0;
select businessid from soldgoods where soldgoodsID = ‘ac63837c76222e4a5419e2529d775ae4‘ for UPDATE;
查询得过结果
开启线程B
执行:
set autocommit=0;
select businessid from soldgoods where soldgoodsID = ‘ac63837c76222e4a5419e2529d775ae4‘ for UPDATE;
查询等待解锁
这个时候在线程A中执行:
update soldgoods set productid = 2 where businessid = ‘0a527df4763c3dc71cbafebec5a8d787‘
不是根据主键而去更新锁表的值
线程B会出现:
[Err] 1213 - Deadlock found when trying to get lock; try restarting transaction
如果将最后线程A中执行的语句改变:
update soldgoods set productid = 2 where soldgoodsID = ‘ac63837c76222e4a5419e2529d775ae4‘
根据索引修改值
然后
commit;
提交事务。线程B就能顺利得到查询值了