鎖是加在索引上的
加鎖規則裡面,包含了兩個「原則」、兩個「優化」和乙個「bug」。
原則 1:加鎖的基本單位是 next-key lock。next-key lock 是前開後閉區間。
原則 2:查詢過程中訪問到的物件才會加鎖。
優化 1:索引上的等值查詢,給唯一索引加鎖的時候,next-key lock 退化為行鎖。
優化 2:索引上的等值查詢,向右遍歷時且最後乙個值不滿足等值條件的時候,next-key lock 退化為間隙鎖。
乙個 bug:唯一索引上的範圍查詢會訪問到不滿足條件的第乙個值為止。
create
table
`demo_table`
(`id`
bigint(20
)not
null
auto_increment
comment
'主鍵'
,`a`
varchar(32
)not
null
comment
'美團訂單uid'
,`b`
varchar(32
)not
null
comment
'美團訂單uid'
,`c`
varchar(32
)not
null
comment
'美團訂單uid'
primary
key(
`id`),
unique
key`a`
(`a`),
key`b`
(`b`),
)engine
=innodb
auto_increment=1
default
charset
=utf8mb4 comment=''
;
唯一索引:a
普通索引:b
無索引列:c
insert
into
`demo_table`
values(1
,1,1
,1),
(2,3
,3,3
),(3
,5,5
,5),
(4,8
,8,8
),(5
,11,11
,11);
select
*from
`demo_table`
where a =
5for
update
;
select
*from
`demo_table`
where b =
5for
update
;
select
*from
`demo_table`
where c =
5for
update
;
MySQL的加鎖規則
首先是課程中的總結的加鎖規則,兩個 原則 兩個 優化 和乙個 bug 可重複讀的事務隔離級別下 原則 1 加鎖的基本單位是 next key lock。希望你還記得,next key lock 是前開後閉區間。原則 2 查詢過程中訪問到的物件才會加鎖。優化 1 索引上的等值查詢,給唯一索引加鎖的時候...
mysql自定義加鎖 為MySQL加鎖?
在日常操作中,update insert delete innodb會自動給涉及的資料集加排他鎖,一般的 select 一般是不加任何鎖的。我們可以使用以下方式顯示的為 select 加鎖。共享鎖 select from table name where id 10 lock in share mo...
MySQL加鎖分析
參考 mysql 加鎖處理分析。該文已經講的很詳盡了,也易懂,下面僅僅是個人做的總結。逐條處理,逐條加鎖。gap鎖是間隙鎖,即相鄰兩條有效記錄間隙的鎖 鎖的是間隙 它是針對insert的,用來解決幻讀的發生。它會阻塞insert,但不會阻塞delete update等 記錄本來也不存在 rc與rr的...