MySQL默認隔離級別REPEATABLE-READ並無解決幻讀問題

刷脈脈,發現一個帖子討論幻讀問題:web

https://maimai.cn/web/gossip_detail?src=app&webid=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlZ2lkIjoiN2JmMjA4ZDZjNzU0MTFlYWExOTk4MDE4NDRlNTAxOTAiLCJ1IjoyMjM0MjgzMTksImlkIjoyNjc0NDU3OH0.yvtEe5Z1vjtmPE5dBwXVqD-pMWBE2--jDQuRARcWArI
app


固作一下實驗,演示下MySQL默認隔離級別REPEATABLE-READ並無解決幻讀問題ide


幻讀演示 spa

MySQL默認隔離級別REPEATABLE-READ(可重複讀)orm

會話一事務

會話二ip

MySQL [test]> select * from t1;ci

+------+get

| id   |it

+------+

|    1 |

|    2 |

|    3 |

|    4 |

+------+

4 rows in set (0.000 sec)

MySQL [test]> select * from t1;

+------+

| id   |

+------+

|    1 |

|    2 |

|    3 |

|    4 |

+------+

4 rows in set (0.000 sec)

MySQL [test]> begin;

Query OK, 0 rows affected (0.000 sec)

 

注:開啓事務一

MySQL [test]> begin;

Query OK, 0 rows affected (0.000 sec)

 

注:開啓事務二

MySQL [test]> insert into t1 values(5);

Query OK, 1 row affected (0.000 sec)

 

MySQL [test]> select * from t1;

+------+

| id   |

+------+

|    1 |

|    2 |

|    3 |

|    4 |

|    5 |

+------+

5 rows in set (0.000 sec)

 

注:插入一條數據5

MySQL [test]> select * from t1;

+------+

| id   |

+------+

|    1 |

|    2 |

|    3 |

|    4 |

+------+

4 rows in set (0.000 sec)

 

注:因會話一未提交,因此在會話二事務裏是看不見更改後的結果的

MySQL [test]> commit;

Query OK, 0 rows affected (0.002 sec)

 

注:會話一執行事務提交



MySQL [test]> select * from t1;

+------+

| id   |

+------+

|    1 |

|    2 |

|    3 |

|    4 |

+------+

4 rows in set (0.000 sec)

 

MySQL [test]> update t1 set id = id+10;

Query OK, 5 rows affected (0.001 sec)

Rows matched: 5  Changed: 5  

Warnings: 0

 

注:執行全表更新,id+10


MySQL [test]> select * from t1;

+------+

| id   |

+------+

|   11 |

|   12 |

|   13 |

|   14 |

|   15 |

+------+

5 rows in set (0.000 sec)

 

注:當再次查看時,此時發現有5條數據被更改,產生幻讀


MySQL [test]> select version();

+-----------+

| version() |

+-----------+

| 8.0.21    |

+-----------+

1 row in set (0.000 sec)

 

MySQL默認隔離級Repeatable Read下,剛纔的操做,在會話二未提交的事務裏,

會莫名其妙地看到第5條數據,這種現象稱爲幻讀。


固只能經過select ... for update才能避免幻讀。

相關文章
相關標籤/搜索