mysql innodb 行鎖解鎖後出現死鎖報錯

轉載自:點擊打開鏈接

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就能順利得到查詢值了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章