mysql 一次死鎖的處理

昨天用apache bench壓操作的時候發生嚴重的死鎖。

查了一下操作:

操作1,insert into tableA 然後 用tableA 的數據 update tableB 

操作2,delete from tableA 然後 用tableA 的數據 update tableB 

用了很小的併發,去執行 操作1後立即執行操作2。發現只有兩條成功,後面的都在等待鎖 。

異常:mysql 'Deadlock found when trying to get lock; try restarting transaction'

從操作上看,兩個操作的順序是對的,不應該發生死鎖。

然後看了sql

操作2:

  1. delete from tableB where SId = 987  

  1. update tableA a  
  2.         JOIN  
  3.     (select   
  4.         '123456' AS CId,  
  5.             count(c.SId) as Count1,  
  6.             IFNULL(SUM(CASE  
  7.                 WHEN s.dType = 'a' THEN 1  
  8.                 ELSE 0  
  9.             END), 0) as Count2,  
  10.             IFNULL(SUM(CASE  
  11.                 WHEN s.dType = 'b' THEN 1  
  12.                 ELSE 0  
  13.             END), 0) as Count3  
  14.     from  
  15.         tableB c  
  16.     left JOIN tableC s ON c.CId = s.Id  
  17.     where  
  18.         c.CId = '123456'as co ON a.Id = co.CId   
  19. set   
  20.     a.Count1 = co.Count1,  
  21.     a.Count2 = co.Count2,  
  22.     a.Count3 = co.Count3  

然後分析認爲後面的sql 在更新tableA時,可能導致了tableB被鎖,因此導致死鎖。

然後把,後面那個sql的查詢的部分拆出來,然後用查詢的結果去更新tableA。

拆出來後發現沒有了死鎖

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