MYSQL批量插入資料庫實現語句效能分析

2022-03-20 20:00:39 字數 2103 閱讀 5804

假定我們的表結構如下

**如下

create table example (

example_id int not null,

name varchar( 50 ) not null,

value varchar( 50 ) not null,

other_value varchar( 50 ) not null

)通常情況下單條插入的sql語句我們會這麼寫:

**如下

insert into example

(example_id, name, value, other_value)

values

(100, 'name 1', 'value 1', 'other 1');

mysql允許我們在一條sql語句中批量插入資料,如下sql語句:

**如下

insert into example

(example_id, name, value, other_value)

values

(100, 'name 1', 'value 1', 'other 1'),

(101, 'name 2', 'value 2', 'other 2'),

(102, 'name 3', 'value 3', 'other 3'),

(103, 'name 4', 'value 4', 'other 4');

如果我們插入列的順序和表中列的順序一致的話,還可以省去列名的定義,如下sql

**如下

insert into example

values

(100, 'name 1', 'value 1', 'other 1'),

(101, 'name 2', 'value 2', 'other 2'),

(102, 'name 3', 'value 3', 'other 3'),

(103, 'name 4', 'value 4', 'other 4');

上面看上去沒什麼問題,下面我來使用sql語句優化的小技巧,下面會分別進行測試,目標是插入乙個空的資料表200w條資料

第一種方法:使用insert into 插入,**如下:

**如下

$params = array('value'=>'50');

set_time_limit(0);

echo date("h:i:s");

for($i=0;$i<2000000;$i++);

echo date("h:i:s");

最後顯示為:23:25:05 01:32:05 也就是花了2個小時多!

第二種方法:使用事務提交,批量插入資料庫(每隔10w條提交下)最後顯示消耗的時間為:22:56:13 23:04:00 ,一共8分13秒 ,**如下:

**如下

echo date("h:i:s");

$connect_mysql->query('begin');

$params = array('value'=>'50');

for($i=0;$i<2000000;$i++)

}$connect_mysql->query('commit');

echo date("h:i:s");

第三種方法:使用優化sql語句:將sql語句進行拼接,使用 insert into table () values (),(),(),()然後再一次性插入,如果字串太長,

則需要配置下mysql,在mysql 命令列中執行 :set global max_allowed_packet = 2*1024*1024*10;消耗時間為:11:24:06 11:25:06;

插入200w條測試資料僅僅用了1分鐘!**如下:

**如下

$sql= "insert into twenty_million (value) values";

for($i=0;$i<2000000;$i++);

$sql = substr($sql,0,strlen($sql)-1);

$connect_mysql->query($sql);

最後總結下,在插入大批量資料時,第一種方法無疑是最差勁的,而第二種方法在實際應用中就比較廣泛,第三種方法在插入測試資料或者其他低要求時比較合適,速度確實快。

MYSQL批量插入資料庫實現語句效能分析

假定我們的表結構如下 如下 create table example example id int not null,name varchar 50 not null,value varchar 50 not null,other value varchar 50 not null 通常情況下單條插...

MYSQL批量插入資料庫實現語句效能分析

假定我們的表結構如下 如下 create table example example id int not null,name varchar 50 not null,value varchar 50 not null,other value varchar 50 not null 通常情況下單條插...

MYSQL批量插入資料庫實現語句效能分析

如下 create table example example id int not null,name varchar 50 not null,value varchar 50 not null,other value varchar 50 not null 通常情況下單條插入的sql語句我們會這...