MySql中測試GUID 與Int自增主鍵 效能對比 總結適用場景
一. 建立以下三個資料表: int 主鍵自增表, guid主鍵表, 關聯以上兩個表的關係表tbl_test_relation
CREATE TABLE `tbl_test_int` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NULL DEFAULT NULL,
`comment` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
COMMENT='測試int主鍵效能'
COLLATE='utf8_general_ci';
CREATE TABLE `tbl_test_measure` (
`code` CHAR(36) NOT NULL,
`deviceID` INT(50) NULL DEFAULT NULL,
`value` INT(50) NULL DEFAULT NULL,
`value2` INT(50) NULL DEFAULT NULL,
PRIMARY KEY (`code`)
)
COMMENT='測試guid作唯一';
CREATE TABLE `tbl_test_relation` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`intvalue` INT(11) NOT NULL DEFAULT '0',
`codevalue` CHAR(36) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci';
二. 向資料表插入資料
Insert into tbl_test_int( name,comment) values
('TestMY', '哈哈,呵呵');
逐條插入,100萬條資料耗時,30分鐘左右
Insert into tbl_test_measure(code,deviceID,value,value2) values ( GUID.NewGuid(), 1,2,3);
逐條插入,100萬條資料耗時2845秒
Insert into tbl_test_relation (intvalue,codevalue)
( select a.id as id , b.code as code from tbl_test_int a , tbl_test_measure b where a.id = b.deviceID
and a.id < 100000 and a.id > 40000 )
再插入到關係表中, 使用時間30秒左右
三.分別查詢其中的效能
select a.id, a.codevalue, b.name from tbl_test_relation a , tbl_test_int b where a.intvalue = b.id limit 10000,80000;
/* Affected rows: 0 已找到記錄: 79,900 警告: 0 持續時間 1 query: 0.110 sec. (+ 0.967 sec. network) */
select a.id, a.codevalue, b.value2,b.value from tbl_test_relation a , tbl_test_measure b where a.codevalue = b.code limit 10000,80000;
/* Affected rows: 0 已找到記錄: 79,900 警告: 0 持續時間 1 query: 0.234 sec. (+ 1.997 sec. network) */
所用時間相差一倍左右
selecta.id,a.codevalue,b.namefromtbl_test_relationa,tbl_test_intbwherea.intvalue=b.idlimit9000,90000;
/* Affected rows: 0 已找到記錄: 80,900 警告: 0 持續時間 1 query: 0.094 sec. (+ 0.998 sec. network) */
/* 更新查詢歷史時出現錯誤: Failed to set data for '1' */
selecta.id,a.codevalue,b.value2fromtbl_test_relationa,tbl_test_measurebwhere a.codevalue=b.codelimit9000,90000;
/* Affected rows: 0 已找到記錄: 80,900 警告: 0 持續時間 1 query: 0.203 sec. (+ 1.856 sec. network) */
/* 更新查詢歷史時出現錯誤: Failed to set data for '1' */
四.測試總結
1.GUID可以確保資料唯一性,資料安全,資料可移植性強,適用於分散式資料庫中相同表的,不同庫中的儲存。 但其中的Select、Update、Insert 相對於Int,在百萬級資料中來講慢一半左右
2.ID使用Int自增做唯一,可以提高資料操作的效能,但需要注意其唯一的操作