一致性读,又称为快照读。使用的是MVCC机制读取undo中的已经提交的数据。所以它的读取是非阻塞的。
相关文档:http://dev.mysql.com/doc/refman/5.6/en/innodb-consistent-read.html
A consistent read means that InnoDB uses multi-versioning to present to a query a snapshot of the database at a point in time. The query sees the changes made by transactions that committed before that point of time, and no changes made by later or uncommitted transactions. The exception to this rule is that the query sees the changes made by earlier statements within the same transaction.
一致性读肯定是读取在某个时间点已经提交了的数据,有个特例:本事务中修改的数据,即使未提交的数据也可以在本事务的后面部分读取到。
1. RC 隔离 和 RR 隔离中一致性读的区别
根据隔离级别的不同,一致性读也是不一样的。不同点在于判断是否提交的“某个时间点”:
1)对于RR隔离:
If the transaction isolation level is REPEATABLE READ (the default level), all consistent reads within the same transaction read the snapshot established by the first such read in that transaction.
文档中说的是:the first such read in that transaction。实际上实验的结果表明,并不是the first such read,而是事务中任何执行的第一条语句为snapshot的起始点,即使该条语句执行失败,也是以它的执行时间为snapshot的起始点。因为事务的起始点其实是以执行的第一条语句为起始点的,而不是以begin作为事务的起始点的。在该起始点之前提交的数据,就可以读取到。(原因应该是RR隔离级别是要支持可重复读的)
实验1:
sesseion A | session B |
mysql> set tx_isolation='repeatable-read'; Query OK, 0 rows affected (0.00 sec)
|
mysql> set tx_isolation='repeatable-read'; Query OK, 0 rows affected (0.00 sec)
|
mysql> begin; Query OK, 0 rows affected (0.01 sec) |
|
mysql> select * from t1; Empty set (0.00 sec)
mysql> insert into t1(c1,c2) values(1,1); Query OK, 1 row affected (0.01 sec) |
|
mysql> select * from t1; +----+------+ | c1 | c2 | +----+------+ | 1 | 1 | +----+------+ 1 row in set (0.00 sec) |
上面的实验说明:RR隔离级别下的一致性读,不是以begin开始的时间点作为snapshot建立时间点,而是以第一条语句的时间点作为snapshot建立的时间点。
实验2:
session A | session B |
mysql> set tx_isolation='repeatable-read'; | mysql> set tx_isolation='repeatable-read'; |
mysql> select * from t1; Empty set (0.00 sec) |
|
mysql> begin;
mysql> set i=1; ERROR 1193 (HY000): Unknown system variable 'i' |
|
mysql> insert into t1(c1,c2) values(1,1); Query OK, 1 row affected (0.01 sec) |
|
mysql> select * from t1; +----+------+ | c1 | c2 | +----+------+ | 1 | 1 | +----+------+ 1 row in set (0.00 sec)
|
该使用说明:RR隔离级别下的一致性读,是以第一语句的执行点作为snapshot建立的时间点的,即使该语句执行失败了,也是如此。
实验3:
session A | session B |
mysql> set tx_isolation='repeatable-read'; |
mysql> set tx_isolation='repeatable-read'; mysql> select * from t1; Empty set (0.00 sec) |
mysql> begin; | |
mysql> select * from t1; Empty set (0.00 sec) |
mysql> select * from t1; Empty set (0.00 sec) |
mysql> insert into t1(c1,c2) values(1,1); | |
mysql> select * from t1; Empty set (0.01 sec) |
该实验中:session A 的第一条语句,发生在session B的 insert语句提交之前,所以session A中的第二条select还是不能读取到数据。因为RR中的一致性读是以事务中第一个语句执行的时间点作为snapshot建立的时间点的。而此时,session B的insert语句还没有执行,所以读取不到数据。
实验4:
session A | session B |
mysql> set tx_isolation='repeatable-read'; |
mysql> set tx_isolation='repeatable-read'; mysql> select * from t1; Empty set (0.00 sec) |
mysql> select * from t1; Empty set (0.00 sec) |
|
mysql> insert into t1(c1,c2) values(1,1),(2,2); mysql> select * from t1; +----+------+ | c1 | c2 | +----+------+ | 1 | 1 | | 2 | 2 | +----+------+ 2 rows in set (0.01 sec) |
|
mysql> select * from t1; Empty set (0.00 sec) |
|
mysql> update t1 set c2=100 where c1=1; Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from t1; +----+------+ | c1 | c2 | +----+------+ | 1 | 100 | +----+------+ 1 row in set (0.00 sec) |
该实验说明:本事务中进行修改的数据,即使没有提交,在本事务中的后面也可以读取到。update 语句因为进行的是“当前读”,所以它可以修改成功。
2)对于RC隔离就简单多了:
With READ COMMITTED isolation level, each consistent read within a transaction sets and reads its own fresh snapshot.
事务中每一次读取都是以当前的时间点作为判断是否提交的实际点,也即是 reads its own fresh snapshot.
RC是语句级多版本(事务的多条只读语句,创建不同的ReadView,代价更高),RR是事务级多版本(一个ReadView);
2. Oracle中的一致性读
Oracle读一致性是指一个查询所获得的数据来自同一时间点。
Oracle读一致性分为语句级读一致性和事务级读一致性。
语句级读一致性:Oracle强制实现语句级读一致性。一个查询语句只读取语句开始之前提交的数据。
事务级读一致性:隔离级别为SERIALIZABLE和read only的事务才支持事务级读一致性。事务中的所有查询语句只读取 事务开始之前提交的数据。
Oracle只实现了RC和serializable,没有实现Read uncommitted 和 RR。其实Oracle的serializable级别才实现了RR可重复读。
3. 当前读(current read) 和 一致性读
一致性读是指普通的select语句,不带 for update, in share mode 等等子句。使用的是undo中的提交的数据,不需要使用锁(MDL除外)。而当前读,是指update, delete, select for update, select in share mode等等语句进行的读,它们读取的是数据库中的最新的数据,并且会锁住读取的行和gap(RR隔离时)。如果不能获得锁,则会一直等待,直到获得或者超时。
4. 一致性读与 mysqldump --single-transaction
我们知道 mysqldump --single-transaction的原理是:设置事务为RR模式,然后利用事务的特性,来获得一致性的数据,但是:
--single-transaction
Creates a consistent snapshot by dumping all tables in a
single transaction. Works ONLY for tables stored in
storage engines which support multiversioning (currently
only InnoDB does); the dump is NOT guaranteed to be
consistent for other storage engines. While a
--single-transaction dump is in process, to ensure a
valid dump file (correct table contents and binary log
position), no other connection should use the following
statements: ALTER TABLE, DROP TABLE, RENAME TABLE,
TRUNCATE TABLE, as consistent snapshot is not isolated
from them. Option automatically turns off --lock-tables.
在mysqldump运行期间,不能执行 alter table, drop table, rename table, truncate table 等等的DDL语句,因为一致性读和这些语句时无法隔离的。
那么在mysqldump --single-transaction 执行期间,执行了上面那些DDL,会发生什么呢?
mysqldump --single-transaction 的执行过程是:设置RR,然后开始事务,对应了一个LSN,然后对所有选中的表,一个一个的执行下面的过程:
save point sp; --> select * from t1 --> rollback to sp;
save point sp; --> select * from t2 --> rollback to sp;
... ...
1> 那么如果对t2表的DDL发生在 save point sp 之前,那么当mysqldump处理到 t2 表时,mysqldump 会立马报错:表结构已经改变......
2> 如果对t2表的DDL发生在 save point sp 之后,rollback to sp 之前,那么要么DDL被阻塞,要么mysqldump被阻塞,具体谁被阻塞,看谁先执行了。
被阻塞额原因是:DDL需要t2表的 MDL 的互斥锁,而select * from t1 需要MDL的共享锁,所以阻塞发生。
3> 如果对t2表的DDL发生在 rollback to sp 之后,那么因为对 t2 表的dump已经完成,不会发生错误或者阻塞。
那么为什么: 对t2表的DDL发生在 save point sp 之前,那么当mysqldump开始处理 t2 表时,mysqldump 立马报错呢?
其原因就是 一致性读的胳膊拗不过DDL的大腿:
Consistent read does not work over certain DDL statements:(一致性读的胳膊拗不过DDL的大腿)
Consistent read does not work over DROP TABLE, because MySQL cannot use a table that has been dropped and InnoDB destroys the table.
Consistent read does not work over ALTER TABLE, because that statement makes a temporary copy of the original table and deletes the original table when the temporary copy is built. When you reissue a consistent read within a transaction, rows in the new table are not visible because those rows did not exist when the transaction's snapshot was taken. In this case, the transaction returns an error as of MySQL 5.6.6: ER_TABLE_DEF_CHANGED, “Table definition has changed, please retry transaction”.
原因:ALTER TABLE, DROP TABLE, RENAME TABLE, TRUNCATE TABLE 这些DDL语句的执行,会导致无法使用undo构造出正确的一致性读,一致性读和它们是无法隔离的。

Stored procedures are precompiled SQL statements in MySQL for improving performance and simplifying complex operations. 1. Improve performance: After the first compilation, subsequent calls do not need to be recompiled. 2. Improve security: Restrict data table access through permission control. 3. Simplify complex operations: combine multiple SQL statements to simplify application layer logic.

The working principle of MySQL query cache is to store the results of SELECT query, and when the same query is executed again, the cached results are directly returned. 1) Query cache improves database reading performance and finds cached results through hash values. 2) Simple configuration, set query_cache_type and query_cache_size in MySQL configuration file. 3) Use the SQL_NO_CACHE keyword to disable the cache of specific queries. 4) In high-frequency update environments, query cache may cause performance bottlenecks and needs to be optimized for use through monitoring and adjustment of parameters.

The reasons why MySQL is widely used in various projects include: 1. High performance and scalability, supporting multiple storage engines; 2. Easy to use and maintain, simple configuration and rich tools; 3. Rich ecosystem, attracting a large number of community and third-party tool support; 4. Cross-platform support, suitable for multiple operating systems.

The steps for upgrading MySQL database include: 1. Backup the database, 2. Stop the current MySQL service, 3. Install the new version of MySQL, 4. Start the new version of MySQL service, 5. Recover the database. Compatibility issues are required during the upgrade process, and advanced tools such as PerconaToolkit can be used for testing and optimization.

MySQL backup policies include logical backup, physical backup, incremental backup, replication-based backup, and cloud backup. 1. Logical backup uses mysqldump to export database structure and data, which is suitable for small databases and version migrations. 2. Physical backups are fast and comprehensive by copying data files, but require database consistency. 3. Incremental backup uses binary logging to record changes, which is suitable for large databases. 4. Replication-based backup reduces the impact on the production system by backing up from the server. 5. Cloud backups such as AmazonRDS provide automation solutions, but costs and control need to be considered. When selecting a policy, database size, downtime tolerance, recovery time, and recovery point goals should be considered.

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

Optimizing database schema design in MySQL can improve performance through the following steps: 1. Index optimization: Create indexes on common query columns, balancing the overhead of query and inserting updates. 2. Table structure optimization: Reduce data redundancy through normalization or anti-normalization and improve access efficiency. 3. Data type selection: Use appropriate data types, such as INT instead of VARCHAR, to reduce storage space. 4. Partitioning and sub-table: For large data volumes, use partitioning and sub-table to disperse data to improve query and maintenance efficiency.

TooptimizeMySQLperformance,followthesesteps:1)Implementproperindexingtospeedupqueries,2)UseEXPLAINtoanalyzeandoptimizequeryperformance,3)Adjustserverconfigurationsettingslikeinnodb_buffer_pool_sizeandmax_connections,4)Usepartitioningforlargetablestoi


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
