为什么 MyISAM 在备份时需要读锁而 Innodb 不需要

why MyISAM requires read lock while backup and Innodb not

请帮助我理解为什么在使用 MyISAM 表备份时需要 READ 锁来保持数据一致性,而 InnoDB 表在备份时不需要 READ 锁。

造成这种差异的原因是 myisam 既没有事务,也没有行级锁定。仅 table 级锁定可用。而 innodb 同时支持事务和行级锁,提供 table 锁的替代方案。但是,您可以选择在备份之前读取 lock innodb tables,这取决于您。

作为 mysql 手册 backup methods 在 myisam 上说:

FLUSH TABLES tbl_list WITH READ LOCK;

You need only a read lock; this enables other clients to continue to query the tables while you are making a copy of the files in the database directory. The flush is needed to ensure that the all active index pages are written to disk before you start the backup.

在 innodb 上,您不必锁定整个 table 以获得一致的数据读取,因为使用适当的事务隔离模式并使用单个事务,这由 innodb 引擎确保。结果与锁定 table 相同,但并发性更好。

同样,上面的链接文档解释了:

For InnoDB tables, it is possible to perform an online backup that takes no locks on tables using the --single-transaction option to mysqldump.

单笔交易选项的文档包含更多详细信息:

This option sets the transaction isolation mode to REPEATABLE READ and sends a START TRANSACTION SQL statement to the server before dumping data. It is useful only with transactional tables such as InnoDB, because then it dumps the consistent state of the database at the time when START TRANSACTION was issued without blocking any applications.

When using this option, you should keep in mind that only InnoDB tables are dumped in a consistent state. For example, any MyISAM or MEMORY tables dumped while using this option may still change state.

While a --single-transaction dump is in process, to ensure a valid dump file (correct table contents and binary log coordinates), no other connection should use the following statements: ALTER TABLE, CREATE TABLE, DROP TABLE, RENAME TABLE, TRUNCATE TABLE. A consistent read is not isolated from those statements, so use of them on a table to be dumped can cause the SELECT that is performed by mysqldump to retrieve the table contents to obtain incorrect contents or fail.