创建表结构

  1. CREATE TABLE `user` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT,
  3. `name` varchar(45) DEFAULT NULL,
  4. `age` int(11) DEFAULT NULL,
  5. `text` varchar(45) DEFAULT NULL,
  6. PRIMARY KEY (`id`),
  7. KEY `idx_name` (`name`),
  8. KEY `idx_age` (`age`),
  9. KEY `idx_name_age` (`name`,`age`)
  10. ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;

初始化数据

  1. INSERT INTO `test_isolation`.`user` (`name`, `age`, `text`) VALUES ('a', '10', 'a');
  2. INSERT INTO `test_isolation`.`user` (`name`, `age`, `text`) VALUES ('b', '20', 'b');
  3. INSERT INTO `test_isolation`.`user` (`name`, `age`, `text`) VALUES ('c', '30', 'c');
  4. INSERT INTO `test_isolation`.`user` (`name`, `age`, `text`) VALUES ('d', '40', 'd');
  5. INSERT INTO `test_isolation`.`user` (`name`, `age`, `text`) VALUES ('e', '50', 'e');

T1 - 设置隔离级别

REPEATABLE READ

  1. SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
  2. select @@global.transaction_isolation,@@transaction_isolation;

image.png

T2 - 设置隔离级别

REPEATABLE READ

  1. SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
  2. select @@global.transaction_isolation,@@transaction_isolation;

image.png

T1 - 事务1开启,第一次查询

T1第一次查询

  1. start transaction;
  2. SELECT * FROM test_isolation.user where id = 6;

image.png

T2 - 事务2开启,插入数据行

插入一条未提交的数据行

  1. start transaction;
  2. INSERT INTO test_isolation.user (`id`, `name`, `age`, `text`) VALUES ('6', 'f', 60, 'f');
  3. SELECT * FROM test_isolation.user;

image.png

T1 - 第2次查询

事务1无法读到了事务2未提交的数据行,避免了脏读

  1. SELECT * FROM test_isolation.user where id = 6;

image.png

T2 - 事务2提交

image.png

T1 - 第3次查询

事务1依然无法读到事务2已提交的数据行,阻止了不可重复读(可以在同一事物中看到相同的数据视图)

  1. SELECT * FROM test_isolation.user where id = 6;

image.png

T1 - 插入了一条T2已经插入并提交的数据f,但是T1在当前事务还无法看到f

  • 既然看不到这条数据为什么无法插入
    1. INSERT INTO test_isolation.user (`id`, `name`, `age`, `text`) VALUES ('6', 'f', 60, 'f');
    image.png

T1 - T1非常困惑,因此T1再次查询是否存在这条记录

  • T1依然无法看到这条记录
    1. SELECT * FROM test_isolation.user where id = 6;
    image.png