mysql行级锁验证过程

行级锁 表锁 参考链接:https://www.cnblogs.com/lushilin/p/6135374.html

采用innodb引擎时,能命中索引就自动使用了行级锁,一些情况下使用表锁更高效时,会自动使用表锁

能否命中索引可用explain命令 在mysql客户端查看,type不为all就算命中。

explain命令 https://www.cnblogs.com/clphp/p/5403215.html

行级锁验证操作步骤:

1、先准备测试表,测试数据 ,索引

create table tab_with_index(id int,name varchar(10)) engine=innodb;

insert into tab_with_index values(1,'1'),(2,'2'),(3,'3'),(4,'4');

alter table tab_with_index add index id(id);

2、打开两个客户端,是为了生成两个进行中的事务,好观察两个事务之间锁的占用

客户端1:

mysql> set autocommit=0;
Query OK, 0 rows affected (0.00 sec)

客户端2:

mysql> set autocommit=0;
Query OK, 0 rows affected (0.00 sec)

3、验证锁对同一行的占用冲突 (普通select不占用锁,加一个for update 执行update操作,对行数据加锁)

客户端1:

select * from tab_with_index where id = 1 for update;

+------+------+
| id   | name |
+------+------+
|    1 | 1    |
+------+------+
1 row in set (0.00 sec)

客户端2:

select * from tab_with_index where id =1  for update;

一直不出来结果

客户端1:

执行commit;可以看到客户端2马上就返回了查询结果,因为客户端1完成事务释放了锁。

客户端2:执行commit;方便接着测试

4、验证不同行的锁不冲突

前提:两个客户端都取消自动提交事务,都执行commit完成当前的事务

客户端1:

select * from tab_with_index where id = 1 for update;

+------+------+
| id   | name |
+------+------+
|    1 | 1    |
+------+------+
1 row in set (0.00 sec)

客户端2:

select * from tab_with_index where id = 2 for update;

+------+------+
| id   | name |
+------+------+
|    2 | 2    |
+------+------+
1 row in set (0.00 sec)

结果:不同行数据不冲突。

看了别人文章的总结:其实是根据索引的值进行锁定,多行数据的索引字段值都为1时,执行select * from tab_with_index where id = 1 for update 会把查出来的行都锁定,

如果用到多个索引时(复合索引),建立的索引第一个字段sql里一定要用到才能命中。

索引顺序对命中的影响:https://blog.csdn.net/u012393450/article/details/78260600

发布了15 篇原创文章 · 获赞 5 · 访问量 9057

猜你喜欢

转载自blog.csdn.net/qq_35702095/article/details/86488864
今日推荐