mysql的有序插入研究

2021-07-03 12:05:38 字數 1951 閱讀 9939

要測試mysql的有序插入,是基於innodb儲存引擎的,先設計以下兩表進行比較,測試**是一致的。下表的插入是屬於有序插入,即不會移動資料項,因為innodb的主鍵是屬於聚簇索引。

create table test_insert_tbl(uid int primary key, age int);

create table test_insert_tbl(id int auto_increment primary key, uid int, age int, unique key(uid));

首先先建立測試原始資料,共200萬條,**如下,上表的插入時間顯著快於下表的時間。

<?php

$dsn = "mysql:host=localhost;dbname=test";

$db = new pdo($dsn, 'root', '');

$db->exec('set autocommit = 0');

$db->exec('set innodb_additional_mem_pool_size = 512m');

$sql = "insert into test_insert_tbl(uid, age) values ";

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

$db->exec($sql.$content);

}for ($i = 0; $i < 1000; ++$i)

$db->exec($sql.$content);

}$db = null;

然後是測試**,如下

<?php

$i = 0;

$arr = array();

while ($i < 1000)

}//echo count($arr);

$t1 = microtime(true);

$dsn = "mysql:host=localhost;dbname=test";

$db = new pdo($dsn, 'root', '');

foreach ($arr as $key => $value)

$db = null;

$t2 = microtime(true);

echo '耗時'.round($t2-$t1,3).'秒';

執行時間結果

上表下表

時間31.741秒

30.824秒

相差無幾,可能是索引的移動也是需要操作,與移動資料項的時間差不多,所以想新增表的列數。新錶加了新的資料項。

create table test_insert_tbl(uid int primary key, age int, name char(20) not null default 'abb', *** char(6) not null default 'male', memo char(255) not null default 'a', memo2 char(255) not null default 'a');

create table test_insert_tbl(id int auto_increment primary key, uid int, age int, name char(20) not null default 'abb', *** char(6) not null default 'male', memo char(255) not null default 'a', memo2 char(255) not null default 'a', unique key(uid));

現在的執行時間

上表下表

時間44.334秒

41.503秒

還是差不多,可能innodb的聚簇索引實現中行資料和葉子節點並非儲存在一起,至少物理上並非儲存在一起,或者儲存並非緊密的,需要研究下**。

有序鍊錶的插入

已知乙個遞增有序鍊錶l 帶頭結點,元素為整數 編寫程式將乙個新整數插入到l中,並保持l的有序 輸入 輸入分三行 第一行 元素個數 第二行 元素的值,元素間用空格分隔。第三行 待插入的元素值 輸出 開頭有空格 code include include include 函式狀態碼定義 define tr...

有序鍊錶的插入

已知乙個遞增有序鍊錶l 帶頭結點,元素為整數 編寫程式將乙個新整數插入到l中,並保持l的有序性。其中單鏈表的型別定義參考如下 typedef int elementtype typedef struct lnode lnode,linklist 輸入分三行 第一行 元素個數 第二行 元素的值,元素間...

有序鍊錶的插入

7 1 有序鍊錶的插入 20 分 已知乙個遞增有序鍊錶l 帶頭結點,元素為整數 編寫程式將乙個新整數插入到l中,並保持l的有序性。其中單鏈表的型別定義參考如下 typedef int elementtype typedef struct lnode lnode,linklist 輸入分三行 第一行 ...