当前位置:网站首页>mysql的行锁和间隙锁
mysql的行锁和间隙锁
2022-08-01 05:29:00 【孤独者的狂欢】
无论是update还是select for update,只要where条件里面字段没有带索引,都会把整个表锁住。如果更新的行上存在索引,更新时锁定被更新的记录。
1、行锁
测试:
item表, 在id、price字段上加锁。
打开两个窗口。 分别关闭自动提交:set autocommit=0;
1.1、字段存在索引,行锁
a窗口执行:
update item2 set stat = 1 where price = 1500;
b窗口执行:
update item2 set stat = 1 where price = 30;

由于price字段存在索引,a窗口的更新语句只锁定了price=1500的一条记录。b窗口正常更新price=30的记录。
1.2、字段不存在索引,表锁
a窗口执行:
update item2 set stat = 1 where name= 'dd';
b窗口执行:
update item2 set stat = 1 where price = 'ee';

由于name字段没有索引,a窗口where限定中name=‘dd’, 没有commit之前, b窗口查询name=‘ee’ 的记录还是被阻塞了。所以如果字段没有索引,在更新时会执行表锁。
1.3、联合索引的情况
新建一个name, address, port三个字段上的联合索引
create index index_name_address_port on item2(name,address,port);

1.3.1、联合索引生效的情况
a窗口执行:
update item2 set stat=1 where name = 'cc4' and address='张家村';
b窗口执行:
update item2 set stat=1 where name = 'ff' and address='bcbc';

联合索引只要where查询索引生效,依然只会锁定行,不会影响其他行的更新。
1.3.2、联合索引没生效的情况
a窗口执行:
update item2 set stat=1 where address='张家村' and port='67';
b窗口执行:
update item2 set stat=1 where address='bcbc' and port='24';

如果where条件中的联合索引失效,依然会锁定整张表。
联合索引生效条件
Mysql从左到右的使用索引中的字段,一个查询可以只使用索引中的一部份,但只能是最左侧部分。例如索引是key index (a,b,c)。 可以支持a | a,b| a,b,c 3种组合进行查找,但不支持 b,c进行查找 .当最左侧字段是常量引用时,索引就十分有效。
2、间隙锁
行锁的一种特殊情况:间隙锁:值在范围内,但却不存在
a窗口执行:
update item2 set stat = 1 where price>100 and price<400;
b窗口执行
INSERT INTO `item2` VALUES (12, 'gt', 'vxc', 234, 288, NULL, NULL);
c窗口执行:
update item2 set stat = 1 where price = 300;


a窗口执行后,b,c窗口都阻塞了。 说明(100,400)的记录都被锁住了。无法插入price在100-400之前的记录, 即使price=288的记录还不存在,可以避免幻度。也无法更新100-400之前已经存在的记录。
边栏推荐
猜你喜欢

PAT serie b write the number 1002

I met a shell script

Flip letters using string container

pytroch、tensorflow对比学习—使用GPU训练模型

AspNet.WebApi.Owin 自定义Token请求参数

2022年湖南工学院ACM集训第六次周测题解

Power button (LeetCode) 212. The word search II (2022.07.31)

从离线到实时对客,湖仓一体释放全量数据价值

SL-12/2过流继电器

Malicious attacks on mobile applications surge by 500%
随机推荐
中国的机器人增长
冲刺金九银十,Android开发面试(内含面试资料|面试题|源码)
matplotlib pyplot
【音视频】srs直播平台搭建
Selenium:下拉框操作
Selenium: JS operation
2022.7.26 模拟赛
leetcode43 string multiplication
移动应用恶意攻击激增500% 三六零天御为APP免费构建安全屏障
Vsce package after the Command failed: NPM list - production - parseable - the depth = 99999 - loglevel = error exception
LeetCode 231. 2 的幂
Robot_Framework:断言
【MySQL必知必会】 表的优化 | 充分利用系统资源
Malicious attacks on mobile applications surge by 500%
七、MFC序列化机制和序列化类对象
微信小程序接口调用凭证(获取token)auth.getAccessToken接口开发
权重等比分配
牛客多校2022第四场A,H,K,N
微信小程序用户登录auth.code2Session接口开发
LeetCode 0150. 逆波兰表达式求值