# create new schemacreate schema test;use test;# create table testcreate table user
( id int primary key,
age int
);alter table user
add index age_idx (age);# insert some test datainsert into user
values (3, 10),
(5, 20),
(8, 30);
2. 间隙锁测试
1. 使用主键索引,指定行存在
1
2
3
4
5
6
7
8
9
# session 1, the row is exist for id = 3 , so it doesn't lock.begin;select * from user where id=3for update;# session 2, execute successful.begin;insert into user value (1, 20);
2. 使用主键索引,指定行不存在
1
2
3
4
5
6
7
8
9
# session 1, the row isn't exist for id = 2, so it locks range (,3]begin;select * from user where id=2for update;# session 2, execute block.begin;insert into user value (1, 20);
3. 使用主键索引,范围查找
1
2
3
4
5
6
7
8
9
# session 1, it locks range [1,5] begin;select * from user where id >=1 and id <=5for update;# session 2, execute blockbegin;insert into user value (2, 20);
4. 使用二级索引,指定行存在
1
2
3
4
5
6
7
8
9
# session 1, it locks range [3,8]begin;select * from user where age=20for update;# session 2, execute block.begin;insert into user value (4, 20);
5. 使用二级索引,指定行不存在
1
2
3
4
5
6
7
8
9
# session 1, it locks range [3,5]begin;select * from user where age=15for update;# session 2, execute block.begin;insert into user value (4, 20);
6. 使用二级索引,范围查询
1
2
3
4
5
6
7
8
9
# session 1, it locks range [3,8]begin;select * from user where age >=12 and age <=28for update;# session 2, execute block.begin;insert into user value (4, 20);