MySQL版本:5.7.29
测试表
CREATE TABLE `test_xrz` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`price` decimal(18,2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin
测试用例
(console_3) 开启事物A,执行以下SQL,不提交事物
select * from test_xrz where id = 2 for update;
update test_xrz set price = 18 where id = 2;
select * from test_xrz; # id=2,price=18
(console)开启事物B,执行以下SQL,不提交事物
select * from test_xrz; # id=2,price=17
select * from test_xrz where id = 2; #id=2,price=17
select * from test_xrz where id = 2 for update ; # waiting...
update test_xrz set price = 14 where id = 2; # waiting...
事物Bfor update
和 update
语句会一直等待
提交事物A
事物A提交后事物Bfor update
和 update
语句才会执行
lock in share mode
for update
是排他锁(不允许其它事物增加任何锁)
lock in share mode
是共享锁(只允许其它事物增加共享锁)