To optimize insert speed, combine many small operations into a single large operation. Ideally, you make a single connection, send the data for many new rows at once, and delay all index updates and consistency checking until the very end.要优化插入速度,请将许多小操作合并到单个大操作中。理想情况下,只建立一个连接,一次发送多个新行的数据,并将所有索引更新和一致性检查延迟到最后。
The time required for inserting a row is determined by the following factors, where the numbers indicate approximate proportions:插入行所需的时间由以下因素决定,其中数字表示近似比例:
Connecting:连接: (3)
Sending query to server:正在向服务器发送查询: (2)
Parsing query:正在分析查询: (2)
Inserting row:插入行: (1 × size of row)
Inserting indexes:插入索引: (1 × number of indexes)
Closing:结束: (1)
This does not take into consideration the initial overhead to open tables, which is done once for each concurrently running query.这并没有考虑打开表的初始开销,对于每个并发运行的查询,打开表只需执行一次。
The size of the table slows down the insertion of indexes by log 假设是B树索引,表的大小会将索引的插入速度按logN
, assuming B-tree indexes.N
降低。
You can use the following methods to speed up inserts:可以使用以下方法加快插入速度:
If you are inserting many rows from the same client at the same time, use 如果要同时从同一客户机插入多行,请使用带有多个值列表的INSERT
statements with multiple VALUES
lists to insert several rows at a time. INSERT
语句一次插入多行。This is considerably faster (many times faster in some cases) than using separate single-row 这比使用单独的单行INSERT
statements. INSERT
语句要快得多(在某些情况下快很多倍)。If you are adding data to a nonempty table, you can tune the 如果要将数据添加到非空表中,可以调整bulk_insert_buffer_size
variable to make data insertion even faster. bulk_insert_buffer_size
变量,使数据插入更快。See Section 5.1.8, “Server System Variables”.请参阅第5.1.8节,“服务器系统变量”。
When loading a table from a text file, use 从文本文件加载表时,请使用LOAD DATA
. LOAD DATA
。This is usually 20 times faster than using 这通常比使用INSERT
statements. INSERT
语句快20倍。See Section 13.2.7, “LOAD DATA Statement”.请参阅第13.2.7节,“LOAD DATA语句”。
Take advantage of the fact that columns have default values. Insert values explicitly only when the value to be inserted differs from the default. 利用列具有默认值这一事实。仅当要插入的值与默认值不同时,才显式插入值。This reduces the parsing that MySQL must do and improves the insert speed.这减少了MySQL必须进行的解析,并提高了插入速度。
See Section 8.5.5, “Bulk Data Loading for InnoDB Tables” for tips specific to 有关InnoDB
tables.InnoDB
表的特定提示,请参阅第8.5.5节,“InnoDB表的批量数据加载”。
See Section 8.6.2, “Bulk Data Loading for MyISAM Tables” for tips specific to 有关MyISAM表的特定提示,请参见第8.6.2节,“MyISAM表的批量数据加载”。MyISAM
tables.