做了一个实验
create table t (id number, mount number);
insert into t value(1,1);
A | B | |
1 | begin; | |
2 | select * from t; | |
3 | begin; | |
4 | select * from t; | |
5 | update t set mount=mount+1 where id = 1; | |
6 | commit; | |
7 | select * from t where id = 1; | |
8 | update t set mount=mount+2 where id = 1; | |
9 | commit; | |
10 | select * from t where id = 1; | |
11 | commit; | |
12 | select * from t where id = 1; | |
13 | commit; | |
result | 12步mount为2 | 7步mount为1,10步mount为4 |
这里事务B的两次结果容让人困惑,从mysql的隔离机制入手就不难理解了
首先7步是为了解决不可重复读,尽管事务A已经修改并提交,但对于事务B不知情,4与7的查询结果应一致,这也是repeatable-read算法,查询时会去寻找事务开始时的snapshot。
那为什么10步会查询为4呢?因为做了update操作,事务的起始点变化为8的位置,寻找到的那时的snapshot.
同样12步只能寻找到事务A最后一次事务操作udpate的shpshot,获得值为2。
另外此机制还可以解决幻读问题,就算事务B进行了INSERT操作,对于不知情的事务A是不会查询到新插入的数据,除非A进行一个事物操作update或者insert。