mysql临键锁的使用

1、默认情况下,innodb使用临键锁锁定记录。

select...forupdate

2、当查询索引包含唯一属性时,临键锁将被优化并降级为记录锁,即只锁定索引本身,而不是范围。

3、不同场景下的临键锁会退化。

实例

事务1

starttransaction;
selectSLEEP(4);
select*fromtestwhereage=22forupdate;
select*fromtestwhereage>23forupdate;
selectsleep(20);
commit;

**************************
事务2

starttransaction;
selectsleep(8);
select*fromtestwhereage=20forupdate;
select*fromtestwhereage=21forupdate;
select*fromtestwhereage=22forupdate;
select*fromtestwhereage=23forupdate;
commit;


************************************
事务执行状态

事务1

starttransaction
>OK
>时间:0s


selectSLEEP(4)
>OK
>时间:4.001s


select*fromtestwhereage=22forupdate
>Affectedrows:0
>时间:0.001s


select*fromtestwhereage>23forupdate
>Affectedrows:0
>时间:0.001s


selectsleep(20)
>OK
>时间:20s


commit
>OK
>时间:0.001s


***********************
事务2

starttransaction
>OK
>时间:0.001s


selectsleep(8)
>OK
>时间:8s


select*fromtestwhereage=20forupdate
>Affectedrows:0
>时间:0.001s


select*fromtestwhereage=21forupdate
>Affectedrows:0
>时间:0.001s


select*fromtestwhereage=22forupdate
>Affectedrows:0
>时间:14.158s


select*fromtestwhereage=23forupdate
>Affectedrows:0
>时间:0.001s


commit
>OK
>时间:0s

以上就是mysql临键锁的使用,希望对大家有所帮助。更多mysql学习指路:MySQL