MySQL for update 是锁表还是锁行
内容来自B站 Java面试题解惑-老杨
根据 id 和 索引 查询是锁行,根据普通字段查询是锁表。



打开两个查询页面就可以测试:
-- 关闭自动提交
-- 关闭自动提交
set @@autocommit = 0;
-- 确认自动提交是否关闭
select @@autocommit;
start transaction;
select * from wise where id = 1 for update;-- 根据id查询,锁行
select * from wise where name = '墨倾池' for update;-- 根据索引查询,锁行
select * from wise where role = '剑者' for update;-- 根据普通字段查询,锁表
commit;
-- 恢复自动提交
set @@autocommit = 1;
-- 确认自动提交是否恢复
select @@autocommit;
-- 关闭自动提交
set @@autocommit = 0;
-- 确认自动提交是否关闭
select @@autocommit;
start transaction;
update wise set role = '剑者' where id = 1;
update wise set role = '智者' where id = 2;
commit;
-- 恢复自动提交
set @@autocommit = 1;
-- 确认自动提交是否恢复
select @@autocommit;
浙公网安备 33010602011771号