昨天用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:
- delete from tableB where SId = 987
- update tableA a
- JOIN
- (select
- '123456' AS CId,
- count(c.SId) as Count1,
- IFNULL(SUM(CASE
- WHEN s.dType = 'a' THEN 1
- ELSE 0
- END), 0) as Count2,
- IFNULL(SUM(CASE
- WHEN s.dType = 'b' THEN 1
- ELSE 0
- END), 0) as Count3
- from
- tableB c
- left JOIN tableC s ON c.CId = s.Id
- where
- c.CId = '123456') as co ON a.Id = co.CId
- set
- a.Count1 = co.Count1,
- a.Count2 = co.Count2,
- a.Count3 = co.Count3
然後分析認爲後面的sql 在更新tableA時,可能導致了tableB被鎖,因此導致死鎖。
然後把,後面那個sql的查詢的部分拆出來,然後用查詢的結果去更新tableA。
拆出來後發現沒有了死鎖