暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

MySQL 可重复读级别下出现幻读的一个例子

背井 2021-03-03
1973

MySQL 默认的隔离级别是 Repeatable Read(可重复读),这种级别下有如下保证:

  1. 不会出现 脏读(dirty reads,即不会读到其它事务未提交的数据);
  2. 可重复读(如其名!,在同一个事务内,一条查询执行2次,其结果一样);
  3. 可能出现幻读(新的数据在特定场景下对该事务可见)。

你可能会比较好奇,幻读何时会发生...


一个常规的可重复读的例子是,对同一张表同时打开2个事务 tx1tx2

tx1:

mysql> begin;

mysql> select * from RepeatRead;
+----+------+
| id | name |
+----+------+
|  1 | jc   |
|  2 | herc |
|  3 | sri  |
+----+------+

tx2:

mysql> begin;

mysql> update percona.RepeatRead set name='ram' where id=3;

mysql> commit;

tx1 还未结束时,tx2 提交了一条更新。此时在 tx1 中进行重复查询时:

tx1:

mysql> select * from RepeatRead;
+----+------+
| id | name |
+----+------+
|  1 | jc   |
|  2 | herc |
|  3 | sri  |
+----+------+

看到的数据并非是 tx2 更新后的数据,仍然和 tx1 中原先的查询结果一致。

这正是 Repeatable Read 所保证的。在这种级别上,SELECT 查询会被打个快照,后续的重复查询则来源于快照。

那么,幻读如何发生?

我们打开两个新的事务,tx3tx4

tx3:

mysql> begin;

mysql> select * from RepeatRead;
+----+------+
| id | name |
+----+------+
|  1 | jc   |
|  2 | herc |
|  3 | sri  |
+----+------+

tx4:

mysql> begin;

mysql> insert into percona.RepeatRead values (4,'ram');

mysql> commit;

我们在 tx3 未结束时,在 tx4 中往表中插入了一条新的数据。

接着,在 tx3 中加入如下语句:

tx3:

mysql> select * from RepeatRead;
+----+------+
| id | name |
+----+------+
|  1 | jc   |
|  2 | herc |
|  3 | sri  |
+----+------+

mysql> update percona.RepeatRead set name='sriram' where id=4;

mysql> select * from RepeatRead;
+----+--------+
| id | name   |
+----+--------+
|  1 | jc     |
|  2 | herc   |
|  3 | sri    |
|  4 | sriram |
+----+--------+

我们看到,再次查询时,仍然保持着「可复复读」;但是,当 update 了 tx4 提交的新数据后,再执行查询时,tx4 中新插入的数据也被 tx3 查出来了!

这就是所说的 「幻读」现象(这种情况下,它和 Read Committed 级别更加相似,即,读取到了另一个事务提交的数据)。

思考:幻读有可能带来什么危害?

- END -


文章转载自背井,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论