- MyISAM只支持表锁,行锁需要使用innodb引擎。
- 加行锁的方法,事务+for update:
start transaction;
select * from joke where id=123 for update;
commit;
其他试图select * from joke where id=123 for update;的进程会阻塞,只到上面的commit或者rollback返回。
但是执行 select * from joke where id=123;的进程不会阻塞。
//a进程执行
start transaction;
select * from joke where id=22565911 for update;
//b进程
select * from joke where id=22565911 for update;
如果没有查询到数据,则不会加锁,b进程不需要等到a进程commit就可以返回。
在非索引字段查询时,mysql将使用表锁。
for update是排它锁,lock in share mode是共享锁,lock in share mode期间不允许修改和删除,但是可以多个读。
for update属于悲观锁,在读多写少的情况下,适合使用乐观锁。
select ver from goods where id=1;
update goods set ver=ver-1 where ver=$ver and ver>0;