I have this table:
create table tab3(
id int not null auto_increment,
phrase text,
link_1 int,
link_2 int,
primary key (id),
foreign key (link_1) references tab1 (id),
foreign key (link_2) references tab2 (id));
I am inserting around 400k rows into this table with Python. this is the insert statement:
INSERT INTO tab3(phrase, link_1, link_2)
VALUES(
%s,
(select id from tab1 where tab1.col1 = %s),
(select id from tab2 where tab2.col2 = %s));
I have an index on both tables tab1.col1 and tab2.col2. but the insertion is taking a long time around 5mins/1000 row
I've tried many different techniques from the official docs of MySQL such as:
- using cursor.execute(stmt,param)
- using cursor.executemany(stmt, params)
- multiple processes ( billiard https://pypi.org/project/billiard/ )
- blocking the commit until all chunk of data is inserted and then commit changes
- encapsulating the insert stmt inside one transaction ( with START TRANSACTION )
But None of the above gave a good improvement.
ENGINE=Memory
. Your goal is not to iterate and insert the rowss one-by-one but perform batch insert, insert all rows with one SQL query.