天天看點

髒讀、幻讀、不可重複讀髒讀不可重複讀幻讀

髒讀

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相同條件查詢多次,但是不可重複度側重點是修改和删除,而幻讀是新增
  • 不可重複度側重對一條資料的查詢,幻讀針對多值查詢或範圍查詢

繼續閱讀