mysql-详解 幻象(phantom)
对于 并发事务情况下产生的一种问题称为 幻象(phantom) ,大部分会翻译为 幻读;
幻读在一定程度上会影响问题认知, 在这里我们首先要理解一个 mysql innodb 引擎中 update 操作的规则 :
update 的执行规则是先读取要更新的行再执行具体的更新操作;
在mysql 的默认隔离级别 repeatable read 情况下实际也会发生幻读, 这里简单使用文字来描述发生的情况(不考虑 gap 锁的情况)
建表语句
CREATE TABLE `test_rr_phantom` (
`id` int unsigned NOT NULL AUTO_INCREMENT primary key,
`a` int unsigned NOT NULL DEFAULT '0' ,
`b` int unsigned NOT NULL DEFAULT '0'
) ENGINE=InnoDB ;
insert into test_rr_phantom (`a`,`b`) values(1,1);
| 时间顺序(依次向下增加) | session1 | session2 |
| t1 | start transaction | |
| t2 |
update `test_rr_phantom` set `a` = 2 where `b` = 1; 对于当前操作会锁定当前(1,1,1)一行 |
|
| t3 | insert into test_rr_phantom(`a`,`b`) values (3,1); 事务自动提交 | |
| t4 | commit |
预测的结果为 : (1,2,1) , (2,3,1) 两条结果数据
实际结果为 : (1,2,1) , (2,2,1)
对于 (2,2,1) 这条数据实际就是 幻读产生的影响, 由于 mysql innodb update 操作 先读后写的规则,对于这里的读是当前读(read current),会读到已提交的数据 (2,3,1), 因此在执行具体的更新操作时 update `test_rr_phantom` set `a` = 2 where `b` = 1 会扫描到两条数据 (1,1,1) ,(2,3,1), 因此最终得到的结果就是 (1,2,1),(2,2,1)
因此在 repeatable read 隔离级别下 幻读实际 就是针对 update 情况下 读到了其他 session 已提交的数据

浙公网安备 33010602011771号