MySQL InnoDB事務的隔離級別有四級,默認是「可重複讀」(REPEATABLE READ)。html
四個級別逐漸加強,每一個級別解決一個問題。mysql
借鑑並改造了一個搞笑的比喻:sql
------session
一些文章寫到InnoDB的可重複讀避免了「幻讀」(phantom read),這個說法並不許確。app
作個試驗:(如下全部試驗要注意存儲引擎和隔離級別)this
mysql> show create table t_bitfly\G;
CREATE TABLE `t_bitfly` (
`id` bigint(20) NOT NULL default '0',
`value` varchar(32) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gbkrestmysql> select @@global.tx_isolation, @@tx_isolation;
+-----------------------+-----------------+
| @@global.tx_isolation | @@tx_isolation |
+-----------------------+-----------------+
| REPEATABLE-READ | REPEATABLE-READ |
+-----------------------+-----------------+code
試驗一:htm
t Session A Session B
|
| START TRANSACTION; START TRANSACTION;
|
| SELECT * FROM t_bitfly;
| empty set
| INSERT INTO t_bitfly
| VALUES (1, 'a');
|
| SELECT * FROM t_bitfly;
| empty set
| COMMIT;
|
| SELECT * FROM t_bitfly;
| empty set
|
| INSERT INTO t_bitfly VALUES (1, 'a');
| ERROR 1062 (23000):
| Duplicate entry '1' for key 1
v (shit, 剛剛明明告訴我沒有這條記錄的)事務
如此就出現了幻讀,覺得表裏沒有數據,其實數據已經存在了,傻乎乎的提交後,才發現數據衝突了。
試驗二:
t Session A Session B
|
| START TRANSACTION; START TRANSACTION;
|
| SELECT * FROM t_bitfly;
| +------+-------+
| | id | value |
| +------+-------+
| | 1 | a |
| +------+-------+
| INSERT INTO t_bitfly
| VALUES (2, 'b');
|
| SELECT * FROM t_bitfly;
| +------+-------+
| | id | value |
| +------+-------+
| | 1 | a |
| +------+-------+
| COMMIT;
|
| SELECT * FROM t_bitfly;
| +------+-------+
| | id | value |
| +------+-------+
| | 1 | a |
| +------+-------+
|
| UPDATE t_bitfly SET value='z';
| Rows matched: 2 Changed: 2 Warnings: 0
| (怎麼多出來一行)
|
| SELECT * FROM t_bitfly;
| +------+-------+
| | id | value |
| +------+-------+
| | 1 | z |
| | 2 | z |
| +------+-------+
|
v
本事務中第一次讀取出一行,作了一次更新後,另外一個事務裏提交的數據就出現了。也能夠看作是一種幻讀。
------
那麼,InnoDB指出的能夠避免幻讀是怎麼回事呢?
http://dev.mysql.com/doc/refman/5.0/en/innodb-record-level-locks.html
By default, InnoDB operates in REPEATABLE READ transaction isolation level and with the innodb_locks_unsafe_for_binlog system variable disabled. In this case, InnoDB uses next-key locks for searches and index scans, which prevents phantom rows (see Section 13.6.8.5, 「Avoiding the Phantom Problem Using Next-Key Locking」).
準備的理解是,當隔離級別是可重複讀,且禁用innodb_locks_unsafe_for_binlog的狀況下,在搜索和掃描index的時候使用的next-key locks能夠避免幻讀。
關鍵點在於,是InnoDB默認對一個普通的查詢也會加next-key locks,仍是說須要應用本身來加鎖呢?若是單看這一句,可能會覺得InnoDB對普通的查詢也加了鎖,若是是,那和序列化(SERIALIZABLE)的區別又在哪裏呢?
MySQL manual裏還有一段:
13.2.8.5. Avoiding the Phantom Problem Using Next-Key Locking (http://dev.mysql.com/doc/refman/5.0/en/innodb-next-key-locking.html)
To prevent phantoms,
InnoDB
uses an algorithm called next-key locking that combines index-row locking with gap locking.You can use next-key locking to implement a uniqueness check in your application: If you read your data in share mode and do not see a duplicate for a row you are going to insert, then you can safely insert your row and know that the next-key lock set on the successor of your row during the read prevents anyone meanwhile inserting a duplicate for your row. Thus, the next-key locking enables you to 「lock」 the nonexistence of something in your table.
個人理解是說,InnoDB提供了next-key locks,但須要應用程序本身去加鎖。manual裏提供一個例子:
SELECT * FROM child WHERE id > 100 FOR UPDATE;
這樣,InnoDB會給id大於100的行(假如child表裏有一行id爲102),以及100-102,102+的gap都加上鎖。
可使用show innodb status來查看是否給表加上了鎖。
再看一個實驗,要注意,表t_bitfly裏的id爲主鍵字段。實驗三:
t Session A Session B
|
| START TRANSACTION; START TRANSACTION;
|
| SELECT * FROM t_bitfly
| WHERE id<=1
| FOR UPDATE;
| +------+-------+
| | id | value |
| +------+-------+
| | 1 | a |
| +------+-------+
| INSERT INTO t_bitfly
| VALUES (2, 'b');
| Query OK, 1 row affected
|
| SELECT * FROM t_bitfly;
| +------+-------+
| | id | value |
| +------+-------+
| | 1 | a |
| +------+-------+
| INSERT INTO t_bitfly
| VALUES (0, '0');
| (waiting for lock ...
| then timeout)
| ERROR 1205 (HY000):
| Lock wait timeout exceeded;
| try restarting transaction
|
| SELECT * FROM t_bitfly;
| +------+-------+
| | id | value |
| +------+-------+
| | 1 | a |
| +------+-------+
| COMMIT;
|
| SELECT * FROM t_bitfly;
| +------+-------+
| | id | value |
| +------+-------+
| | 1 | a |
| +------+-------+
v
能夠看到,用id<=1加的鎖,只鎖住了id<=1的範圍,能夠成功添加id爲2的記錄,添加id爲0的記錄時就會等待鎖的釋放。
MySQL manual裏對可重複讀裏的鎖的詳細解釋:
http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
For locking reads (
SELECT
withFOR UPDATE
orLOCK IN SHARE MODE
),UPDATE
, andDELETE
statements, locking depends on whether the statement uses a unique index with a unique search condition, or a range-type search condition. For a unique index with a unique search condition,InnoDB
locks only the index record found, not the gap before it. For other search conditions,InnoDB
locks the index range scanned, using gap locks or next-key (gap plus index-record) locks to block insertions by other sessions into the gaps covered by the range.
------
一致性讀和提交讀,先看實驗,實驗四:
t Session A Session B
|
| START TRANSACTION; START TRANSACTION;
|
| SELECT * FROM t_bitfly;
| +----+-------+
| | id | value |
| +----+-------+
| | 1 | a |
| +----+-------+
| INSERT INTO t_bitfly
| VALUES (2, 'b');
| COMMIT;
|
| SELECT * FROM t_bitfly;
| +----+-------+
| | id | value |
| +----+-------+
| | 1 | a |
| +----+-------+
|
| SELECT * FROM t_bitfly LOCK IN SHARE MODE;
| +----+-------+
| | id | value |
| +----+-------+
| | 1 | a |
| | 2 | b |
| +----+-------+
|
| SELECT * FROM t_bitfly FOR UPDATE;
| +----+-------+
| | id | value |
| +----+-------+
| | 1 | a |
| | 2 | b |
| +----+-------+
|
| SELECT * FROM t_bitfly;
| +----+-------+
| | id | value |
| +----+-------+
| | 1 | a |
| +----+-------+
v
若是使用普通的讀,會獲得一致性的結果,若是使用了加鎖的讀,就會讀到「最新的」「提交」讀的結果。
自己,可重複讀和提交讀是矛盾的。在同一個事務裏,若是保證了可重複讀,就會看不到其餘事務的提交,違背了提交讀;若是保證了提交讀,就會致使先後兩次讀到的結果不一致,違背了可重複讀。
能夠這麼講,InnoDB提供了這樣的機制,在默認的可重複讀的隔離級別裏,可使用加鎖讀去查詢最新的數據。
http://dev.mysql.com/doc/refman/5.0/en/innodb-consistent-read.html
If you want to see the 「freshest」 state of the database, you should use either the READ COMMITTED isolation level or a locking read:
SELECT * FROM t_bitfly LOCK IN SHARE MODE;
------
結論:MySQL InnoDB的可重複讀並不保證避免幻讀,須要應用使用加鎖讀來保證。而這個加鎖度使用到的機制就是next-key locks。