本节描述了使用 InnoDB 表时的最佳实践。This section describes best practices when using
InnoDB tables.
为每个表指定主键,使用查询最频繁的列或列组合,如果没有明显的主键,则使用自增值。Specify a primary key for every table using the most frequently queried column or columns, or an auto-increment value if there is no obvious primary key.
当从多个表基于这些表中相同的 ID 值提取数据时,请使用连接。为了获得快速的连接性能,在连接列上定义外键,并在每个表中声明这些列具有相同的数据类型。添加外键可确保引用的列被索引,从而提高性能。外键还会将删除和更新传播到所有受影响的表,并且如果父表中不存在相应的 ID,则防止在子表中插入数据。Use joins wherever data is pulled from multiple tables based on identical ID values from those tables. For fast join performance, define foreign keys on the join columns, and declare those columns with the same data type in each table. Adding foreign keys ensures that referenced columns are indexed, which can improve performance. Foreign keys also propagate deletes and updates to all affected tables, and prevent insertion of data in a child table if the corresponding IDs are not present in the parent table.
关闭自动提交。每秒提交几百次会限制性能(受存储设备写入速度的限制)。Turn off autocommit. Committing hundreds of times a second puts a cap on performance (limited by the write speed of your storage device).
通过使用
START TRANSACTION和COMMIT语句将相关的 DML 操作组合到事务中。虽然不希望过于频繁地提交,但也不希望执行大量INSERT、UPDATE或DELETE语句而长时间不提交。Group sets of related DML operations into transactions by bracketing them withSTART TRANSACTIONandCOMMITstatements. While you don't want to commit too often, you also don't want to issue huge batches ofINSERT,UPDATE, orDELETEstatements that run for hours without committing.不要使用
LOCK TABLES语句。InnoDB可以处理多个会话同时对同一张表进行读写,而不会牺牲可靠性或高性能。若要对一组行获得独占写访问权限,请使用SELECT ... FOR UPDATE语法,只锁定您打算更新的行。Do not useLOCK TABLESstatements.InnoDBcan handle multiple sessions all reading and writing to the same table at once without sacrificing reliability or high performance. To get exclusive write access to a set of rows, use theSELECT ... FOR UPDATEsyntax to lock just the rows you intend to update.启用
innodb_file_per_table变量或使用通用表空间,将表的数据和索引放入单独的文件中,而不是放入系统表空间。innodb_file_per_table变量默认启用。Enable theinnodb_file_per_tablevariable or use general tablespaces to put the data and indexes for tables into separate files instead of the system tablespace. Theinnodb_file_per_tablevariable is enabled by default.评估您的数据和访问模式是否能从
InnoDB表或页压缩功能中受益。您可以在不牺牲读写能力的情况下压缩InnoDB表。Evaluate whether your data and access patterns benefit from theInnoDBtable or page compression features. You can compressInnoDBtables without sacrificing read/write capability.使用
--sql_mode=NO_ENGINE_SUBSTITUTION选项运行服务器,以防止表使用您不想使用的存储引擎创建。Run the server with the--sql_mode=NO_ENGINE_SUBSTITUTIONoption to prevent tables from being created with storage engines that you do not want to use.