当前位置:网站首页>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之前已经存在的记录。
边栏推荐
猜你喜欢

对话MySQL之父:一个优秀程序员可抵5个普通程序员

AspNet.WebApi.Owin custom Token request parameters

Robot_Framework:断言

混合型界面:对话式UI的未来

牛客多校2022第四场A,H,K,N

(2022 Niu Ke Duo School IV) K-NIO's Sword (Thinking)

2022.7.26 Mock Competition

Qt Widget project loading example of qml

The solution to the inconsistency between the PaddleX deployment inference model and the GUI interface test results

可持久化线段树
随机推荐
使用string 容器翻转 字母
PaddleX部署推理模型和GUI界面测试结果不一致的解决方法
字符中的第一个唯一字符
LeetCode 9. 回文数
Selenium:表单切换
Selenium: Element wait
leetcode125 验证回文串
About making a progress bar for software initialization for Qt
leetcode43 string multiplication
深度比较两个对象是否相同
微信小程序获取手机号phonenumber.getPhoneNumber接口开发
pytroch、tensorflow对比学习—搭建模型范式(低阶、中阶、高阶API示例)
LeetCode 27. 移除元素
Vsce package after the Command failed: NPM list - production - parseable - the depth = 99999 - loglevel = error exception
类神经网络训练不起来怎么办
NUMPY
Solve the problem of page flicker caused by browser scroll bars
可持久化线段树
Robot_Framework: keyword
WPF入门项目必知必会-初步了解数据绑定 binding