面试官问:select......for update会锁表还是锁行?
00 分钟
2023-8-8
2023-11-6
type
status
date
slug
summary
tags
category
icon
password
URL
select查询语句是不会加锁的,但是select .......for update除了有查询的作用外,还会加锁呢,而且它是悲观锁。
那么它加的是行锁还是表锁,这就要看是不是用了索引/主键。
没用索引/主键的话就是表锁,否则就是是行锁。

验证:

建表sql
需要关闭自动提交,通过set @@autocommit=0; 设置为手动提交。0代表手动提交,1代表自动提交。
notion image

结合一下实例验证

实例1:
使用主键id为条件去查询,然后开启另一个事务去更新数据,更新被阻塞,加锁了,锁定要查询的id为1的行数据。
  • 图一为第一个事务,并且没有提交事务
  • 图二为第二个事务,去更新数据,被阻塞了
  • 图三为第二个事务,长时间拿不到锁报错。
notion image
notion image
notion image
实例2:
我们在开启一个事务对另一条id为2的数据进行更新,
notion image
notion image
实例3(索引):
一开始的创建表就age创建了唯一索引。
notion image
notion image
notion image
实例4:
使用普通的字段code去操作
notion image
notion image
notion image
另一个事务我去更新另外一条数据,如果我更新成功了,就是锁行,失败了就是锁表。
notion image
notion image

结果:

如果查询条件用了索引/主键,那么select ..... for update就会进行行锁。
如果是普通字段(没有索引/主键),那么select ..... for update就会进行锁表。

评论