
定义数据如下:
CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMNT , `age` int(11) DEFAULT NULL , PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 ; CREATE TABLE `other_table` ( `id` int(11) NOT NULL AUTO_INCREMENT , `age` int(11) DEFAULT NULL , PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 ; INSERT other_table VALUE (1,1); INSERT other_table VALUE (2,1); INSERT user VALUE (1,1); INSERT user VALUE (2,1); 案例一--MVCC: Mysql 默认的 RR 隔离级别下,理论上快照读会获取当前事务开启时的数据快照。
AB 事务按以下顺序执行
1A: start transaction; 2B: start transaction; 3B update user set age=20 where id =2 ; 4A select * from other_table where id =2 ; 5B COMMIT; 6A select age from user where id =3 for update; 7A select age from user where id =3 ; 语句 6,7 分别返回 age=20 age=2,这个符合我们对 MVCC 的一般认知。 然而将对无关表的查询--语句 4 抽离时
1A: start transaction; 2B: start transaction; 3B update user set age=20 where id =2 ; 4B COMMIT; 5A select age from user where id =3 for update; 6A select age from user where id =3 ; 这时语句 5,6 返回的都是 age=30。 这现象是在解决线上一个并发 BUG 时无意发现的。 select * from other_table where id =2 ;对表空间的 UNDO 段没有任何影响,却影响了快照读的结果。 一开始我以为这个可能是 Mysql 查询缓存的一个 BUG,直到我做了另外一个实验。
案例二:alter table 导致 table meta change 还是那个两个测试表,
1.A start transaction; 2.A select * from other_table where id =2 ; 3.B ALTER TABLE user ADD COLUMN `age2` int(5) DEFAULT NULL ; 4.A select * from user where id =2 ; 因为同一个事务中表格 meta data 改变,执行语句 4 时 mysql 抛出报错 ERROR 1412 (HY000): Table definition has changed, please retry transaction
这次我们估计重施,将语句 2 抽调
1.A start transaction; 2.B ALTER TABLE user ADD COLUMN `age3` int(5) DEFAULT NULL ; 3.A select * from user where id =2 ; 语句 3 成功返回,没有任何报错:
+----+------+------+------+ | id | age | age2 | age3 | +----+------+------+------+ | 2 | 30 | NULL | NULL | +----+------+------+------+ 到了这里我开始确认,案例 1 并不是 1 个 BUG,而是 mysql 的'start transaction'并没有真正开启一个事务。 在'start transaction'后,很可能 mysql 在执行第一条查询时,才算完全开启了一个事务。
|      1bromineMai OP 居然直接沉了.. | 
|  |      2HelloAmadeus      2019-03-21 13:00:49 +08:00 via iPhone alert 难道可以用在事务里了吗? |