mysql for update 锁行的错误理解

1. 最开始的理解是 : for update 会对查询出的结果加行锁,没有查询到结果就不加锁。 

但是今天发现有一句代码执行for update 却超时了 。查了mysql 获取锁超时时间是 50s . 

已我目前业务量不可能有 某一行 被单独锁定50s 。 除非是整表有锁,导致获取单独行锁超时。

排查发现的确是表锁。 

正确锁行的理解: for update 会对 经过索引(包含主键, 此处注意《经过索引》,下面会说明)查询出的结果行 加行锁,否则就会加表锁。 

举例:表 t_log  , 主键 sys_uuid , 普通索引列 mer_order_no , 普通列 chk_trans_no  。 列类型都是Varchar

sys_uuid mer_order_no chk_trans_no
1 1 1
2 2 2

以下需要开启两个命令行,navicat 在tools - console 下。 C1- 命令行1 , C2 - 命令行2 

1. C1:   start transaction ; select * from t_log where chk_trans_no= 1  for update;   (开启事务不commit)

    C2:      select * from t_log where chk_trans_no= 2  for update;  

  发现C2 卡住,C1 commit 后就执行了。  说明 对非索引列使用 for update  是表锁

 

2. C1:   start transaction ; select * from t_log where mer_order_no = 1  for update;  

    C2:      select * from t_log where mer_order_no = 2  for update;  

  发现C2 仍然卡住 , mer_order_no 是索引列 啊 , 这是为何?原因在类型Varchar ,  数字1 会导致mysql 自动执行

类型转换,而自动类型转换索引失效(可以使用 explain sql 看清楚), 所以我上面强调是通过索引查询出的结果, 而

这时候并不是通过索引查询出的行,所以加的是表锁。  

把1 和 2  换成 ‘1’ , '2' 。 C2 就不会卡住了,说明是行锁。 

 

其他说明: 对一张表加行锁后, 在想加表锁,需要等待行锁释放。 

C1:   start transaction ; select * from t_log where mer_order_no = ‘1’  for update;  

C2:   select * from t_log where chk_trans_no= 2  for update;  (由于无索引会尝试加表锁,等待C1 释放)

 

  综上: 请慎用for update , 如果用请配置好索引。

 

 参考: https://www.cnblogs.com/liangge0218/archive/2013/03/26/3292381.html

 

 

 

 

posted on 2019-11-22 13:57  远方的人  阅读(1565)  评论(0编辑  收藏  举报

导航