脏读
P1 (“Dirty read”): SQL-transaction T1 modifies a row. SQL-
transaction T2 then reads that row before T1 performs a COMMIT.
If T1 then performs a ROLLBACK, T2 will have read a row that was
never committed and that may thus be considered to have never
existed.
一个事务读取到了其他事务中修改未提交的数据。
举例
id | name |
---|---|
1 | 张三 |
- session1 开启了事务并且将
张三
改为了李四
,但是事务不进行提交。 - 那么session2再去读取id为1的数据,发现本来的张三变成了李四。这就叫脏读,因为事务未提交。
不可重复读
P2 (“Non-repeatable read”): SQL-transaction T1 reads a row. SQL-
transaction T2 then modifies or deletes that row and performs
a COMMIT. If T1 then attempts to reread the row, it may receive
the modified value or discover that the row has been deleted.
一个事物第一次读取数据后,其他事务进行了修改或删除并提交,当前事务再次读取时和前一次读取的数据不一致。
举例
还是上边的数据。
- session1 开启事务,读取id=1的数据,发现名字是张三
- session2 这个时候对id=1的数据改为了李四并提交事务
- 这个时候session1 重新select了一遍id=1的数据,发现本来是张三的数据变成了李四,造成了两次读取的结果不一样
上面的情形就是不可重复读,同一个数据在同一个事务内两次读取到的数据不一致。
不可重复读和脏读的区别
- 脏读是修改后事务不进行提交,不可重复读是事务在修改或删除完后数据正常提交
- 不可重复读是在同一事物内读取同一数据多次而结果不一致
幻读
P3 (“Phantom”): SQL-transaction T1 reads the set of rows N
that satisfy some . SQL-transaction T2 then
executes SQL-statements that generate one or more rows that
satisfy the used by SQL-transaction T1. If
SQL-transaction T1 then repeats the initial read with the same
, it obtains a different collection of rows.
一个事物第一次读取数据后,其他事务进行了插入操作,造成当前事务再次读取时和前一次读取的数据不一致。
举例
- session1 开启事务,读取数据id>0的数据,这时我们读取到了 id=1的张三,数据总数为1条
- session2 插入了id=2 的李四并提交事务
- session1 再次读取id>0的数据 这时 id=1 和id=2 都能够读取到,数据总条数变成了2条
幻读和不可重复度的区别
- 两者的操作都是session1相同条件查询多次,但是不可重复度侧重点是修改和删除,而幻读是新增
- 不可重复度侧重对一条数据的查询,幻读针对多值查询或范围查询