最近再找一些Mysql鎖表原因,整理出來一部分sql語句會鎖表的,方便查閱,整理的不是很全,都是工作中碰到的,會持續更新
筆者能力有限,如果有不正確的,或者不到位的地方,還請大家指出來,方便你我,方便大家。
此測試環境
Mysql 5.5 基於innodb 引擎
insert into table1 values select … from table2 ….
此種方法,會鎖table2
delete table1 from table1 inner join table2 on table1.id=table2.id …
此種方法,會鎖table2
update tabel1,table2 set table1.name=’feie’ where table1.id=table2.id
此種方法,會鎖table2
update tabel1,table2 set table1.name=’feie’ where table1.id=table2.id and table1.id=1;
此種方法,會鎖table2.id=1的記錄
-----------------------------------------第二次編輯分割線--------------------------------------
假設kid 是表table 的 一個索引字段 且值不唯一
1.如果kid 有多個值爲12的記錄那麼:
update table set name=’feie’ where kid=12;
會鎖表
2.如果kid有唯一的值爲1的記錄那麼:
update table set name=’feie’ where kid=1;
不會鎖
總結:用索引字段做爲條件進行修改時, 是否表鎖的取決於這個索引字段能否確定記錄唯一,當索引值對應記錄不唯一,會進行鎖表,相反則行鎖。
如果有兩個delete
kid1 與 kid2是索引字段
語句1 delete from table where kid1=1 and kid2=2;
語句2 delete from table where kid1=1 and kid2=3;
這樣的兩個delete 是不會鎖表的
語句1 delete from table where kid1=1 and kid2=2;
語句2 delete from table where kid1=1 ;
這樣的兩個delete 會鎖表
總結:同一個表,如果進行刪除操作時,儘量讓刪除條件統一,否則會相互影響造成鎖表
mysql批量更新update操作,導致鎖表
sql如下:
update pay_trans
set return_state = 1
WHERE
order_id = #{orderId}
and user_id = #{userId}
批量執行此條sql時,導致數據表被鎖,所有交易異常。
經排查where條件order_id and user_id 沒有加索引,導致整個表被鎖。
mysql的行鎖是通過索引加載的,即是行鎖是加在索引響應的行上的,要是對應的SQL語句沒有走索引,則會全表掃描,
行鎖則無法實現,取而代之的是表鎖。
簡而言之:where條件裏面,不加索引時,update會使用“表鎖”進行更新,影響所有行的查詢更新;
加了索引後,使用“行鎖”進行udpate,只鎖當前行。不影響其他行的查詢更新。
http://blog.csdn.net/u014453898/article/details/56068841
http://www.cnblogs.com/zmduan/p/5033047.html