为什么在通过脚本和INSERT SELECT创建表时会有如此巨大的差异?

Jim*_*Jim 0 mysql perl performance create-table

我创建了一个小的Perl脚本来向表中插入大量条目.
示例代码段:

$query = "insert into big_table (first_name, last_name) values (?, ?) ";

# prepare your statement for connecting to the database
$statement = $connection->prepare($query);

for(my $i = 1; $ i <= 70000; i++) {  
    my $first = "test".$i;  
    my $last = "test".$i;   
    $statement->execute($first, $last);   
}  
Run Code Online (Sandbox Code Playgroud)

它插入行,大约需要15分钟

但是当我这样做时:

CREATE TABLE big_table2 like big_table;  
INSERT INTO big_table2 SELECT * FROM big_table;  
Run Code Online (Sandbox Code Playgroud)

只花了55秒!对于70000行为
何如此巨大的差异?

ale*_*oot 6

要加快循环插入速度,您可以尝试使用事务:

添加 AutoCommit=>0属性到连接:

my $connection = DBI->connect($dsn,$username,$password, AutoCommit=>0); # transaction enabled
Run Code Online (Sandbox Code Playgroud)

然后在for循环之后,您可以在单个原子操作中提交所有更改:

$connection->commit();
Run Code Online (Sandbox Code Playgroud)

你注意到的性能差异在你在for循环中执行的几个操作中是不可改变的,你正在执行一个查询并写入磁盘70000次,而另一个查询只有一次所有记录...