简体   繁体   中英

InnoDB: Bulk insert using transaction OR combine multiple queries?

When doing a bulk INSERT in InnoDB, should I use a transaction

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.

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

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. This is considerably faster (many times faster in some cases) than using separate single-row INSERT statements. If you are adding data to a nonempty table, you can tune the bulk_insert_buffer_size variable to make data insertion even faster.

The 1st version is technically not bulk insert, you are inserting 1 record at a time. 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.

To speed up the insertion of massdata into innodb tables consider

  • turning off autocommit mode
  • turning off unique key checks
  • turning off foreignkey checks

See mysql documentation on these

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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