简体   繁体   English

InnoDB:使用事务批量插入或组合多个查询?

[英]InnoDB: Bulk insert using transaction OR combine multiple queries?

When doing a bulk INSERT in InnoDB, should I use a transaction在 InnoDB 中进行批量INSERT时,我应该使用事务吗

START TRANSACTION;
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3);
INSERT INTO tbl_name (a,b,c) VALUES(4,5,6);
INSERT INTO tbl_name (a,b,c) VALUES(7,8,9);
COMMIT TRANSACTION;

Or combine multiple queries?或者组合多个查询?

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

If it matters, I'm using PHP and the MySQL database is on the same machine.如果重要的话,我使用的是 PHP 并且 MySQL 数据库在同一台机器上。

I'd recommend combining multiple queries like you have in the bottom example.我建议像底部示例中那样组合多个查询。

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

If either of the value-pair fails, none of the data will be inserted.如果任何一个值对失败,则不会插入任何数据。 This method also sends less characters and round-trip to the DB.此方法还向数据库发送较少的字符和往返。 The implication of less characters may not be that attractive but it still holds slight advantage.较少字符的含义可能没有那么吸引人,但它仍然具有轻微的优势。

EDIT:编辑:

Tim has a great question.蒂姆有一个很好的问题。 Let me include information from MySQL doc让我包含MySQL 文档中的信息

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.如果您同时从同一客户端插入多行,请使用带有多个 VALUES 列表的 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 变量以加快数据插入速度。

The 1st version is technically not bulk insert, you are inserting 1 record at a time.第一个版本在技术上不是批量插入,您一次插入 1 条记录。 That's the slowest possible method to import large amount of data.这是导入大量数据最慢的方法。

The 2nd option is called bulk insert and is a lot faster.第二个选项称为批量插入,速度要快得多。

However, you can use transactions with bulk insert as well.但是,您也可以将事务与批量插入一起使用。

The 3rd option is to load data with LOAD DATA INFILE command, which is even faster.第三个选项是使用LOAD DATA INFILE命令加载数据,它甚至更快。

To speed up the insertion of massdata into innodb tables consider要加快将大量数据插入 innodb 表的速度,请考虑

  • turning off autocommit mode关闭自动提交模式
  • turning off unique key checks关闭唯一键检查
  • turning off foreignkey checks关闭外键检查

See mysql documentation on these请参阅有关这些的 mysql 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM