製作mysql大數據表驗證覆蓋索引

  • 2019 年 10 月 3 日
  • 筆記

昨天跟同事聊起數據表性能的問題,能不能僅用覆蓋索引實現數據的匯總統計。找了一個開發環境已有的數據表進行測試,通過explain命令,能看到mysql通過覆蓋索引就能實現sum的需求,而無須去讀取實際行數據。

但開發環境數據量太小,對執行時間的優化,沒有直觀感受,於是決定做一個數據量能到千萬級的數據表,方便測試。寫個java程序來填充隨機數據是第一選擇,但還要動用IDE太麻煩,嘗試直接使用mysql的函數來實現。

1     數據表設計

目的是演示如何生成千萬級數據,只設計了一個最簡單常用的數據表:user。

CREATE TABLE `user` (    `user_id` bigint(20) NOT NULL AUTO_INCREMENT,    `account` varchar(32) COLLATE utf8_bin NOT NULL,    `password` varchar(128) COLLATE utf8_bin NOT NULL,    `name` varchar(32) COLLATE utf8_bin NOT NULL,    `email` varchar(64) COLLATE utf8_bin DEFAULT NULL,    `mobile` varchar(20) COLLATE utf8_bin DEFAULT NULL,    `age` int(10) unsigned NOT NULL DEFAULT 0,    PRIMARY KEY (`user_id`)  ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

2     編寫函數/過程

mysql的rand()函數,返回的是一個隨機浮點數。為了實現隨機插入數據,將基於這個函數實現。

2.1     獲取隨機整數

CREATE FUNCTION `getRandomInt`(`maxValue` int) RETURNS int(11)  BEGIN    DECLARE randomInt int default 0;    SET randomInt = FLOOR(rand() * `maxValue`);    RETURN randomInt;  END

2.2     獲取隨機字符串

CREATE FUNCTION `getRandomString`(`length` int) RETURNS varchar(128) CHARSET utf8 COLLATE utf8_bin  BEGIN    DECLARE result VARCHAR(128) default '';    DECLARE chars varchar(30) default 'abcdefghijklmnopqrstuvwxyz';  #全小寫字母    DECLARE charIndex int default 0;    WHILE length > 0 DO      SET charIndex = getRandomInt(26);      SET result = concat(result, SUBSTRING(chars, charIndex + 1, 1));      SET length  = length - 1;    END WHILE;    RETURN result;  END

2.3     獲取隨機手機號

11位手機號,必須1開始,後續10位只要是數字就行,有點不符合現在的手機號規則。

CREATE FUNCTION `getRandomMobile`() RETURNS varchar(128) CHARSET utf8 COLLATE utf8_bin  BEGIN    DECLARE result VARCHAR(128) default '1';    DECLARE chars varchar(30) default '123456789';    DECLARE charIndex int default 0;    DECLARE length int DEFAULT 10;    WHILE length > 0 DO      SET charIndex = getRandomInt(9);      SET result = concat(result, SUBSTRING(chars, charIndex + 1, 1));      SET length  = length - 1;    END WHILE;    RETURN result;  END

2.4     獲取隨機漢字

中文漢字的unicode,是從0X4E00(19968)開始的,寫個函數隨機從前2000個漢字中讀出一個。這兒要注意的是char的方法,想生成漢字要使用 using utf16。實測生成的數據存入到 utf8 編碼的數據表字段中,能正確顯示。

CREATE FUNCTION `getRandomChineseChar`() RETURNS varchar(2) CHARSET utf8  BEGIN    DECLARE charValue int DEFAULT 19968;    SET charValue = charValue + getRandomInt(2000);    RETURN char(charValue using utf16);  END

2.5     獲取隨機姓名

姓名還不能完全使用隨機漢字,“姓”我決定從百家姓里取前兩百個。貼出來的代碼中字符串不完整,感興趣的自己上網查下來補一下就行。

CREATE FUNCTION `getRandomChineseName`() RETURNS varchar(20) CHARSET utf8  BEGIN    DECLARE LAST_NAMES VARCHAR(300) DEFAULT '趙錢孫李周吳鄭王...';    DECLARE chineseName varchar(20) default '';    SET chineseName = SUBSTRING(LAST_NAMES, getRandomInt(200) + 1, 1);    SET chineseName = concat(chineseName, getRandomChineseChar());    SET chineseName = concat(chineseName, getRandomChineseChar());    RETURN chineseName;  END

2.6     插入隨機用戶數據

在這個過程中實現真正插入用戶數據。

CREATE PROCEDURE `createRandomUser`(IN `count` int)  BEGIN    DECLARE userCount DECIMAL(10) default 0;      DECLARE account VARCHAR(32) DEFAULT '';    DECLARE thePassword VARCHAR(128) DEFAULT '';    DECLARE theName VARCHAR(32) DEFAULT '';    DECLARE email VARCHAR(64) DEFAULT '';    DECLARE mobile VARCHAR(20) DEFAULT '';    DECLARE age int DEFAULT 0;      WHILE userCount < `count` DO      SET account = getRandomString(10);      SET thePassword = getRandomString(20);      SET theName = getRandomChineseName();      SET email = concat(account, '@codestory.tech');      SET mobile = getRandomMobile();      SET age = 10 + getRandomInt(50); #年齡10-60歲        insert into user values(null, account, thePassword, theName, email, mobile, age);      SET userCount = userCount + 1;    END WHILE;  END 

3     生成數據

執行過程,就可以生成相應的數據。如下代碼生成100行

[SQL] call createRandomUser(100);  受影響的行: 100  時間: 1.004s

我電腦上這個表的數據行數

mysql> select count(*) from userG;  *************************** 1. row ***************************  count(*): 10001102  1 row in set (5.70 sec)

如下是我生成的部分數據

  

4     索引對查詢性能的影響

設計一個簡單的查詢:所有趙姓用戶且手機號139開頭,平均年齡是多少?

測試SQL,以及查看執行情況

select count(user_id), avg(age) from user where name like '趙%' and mobile like '139%'G;  explain select count(user_id), avg(age) from user where name like '趙%' and mobile like '139%'G;

4.1     只有主鍵的情況

我們前面創建數據表時,只設置了主鍵,沒有創建任何索引。這時候執行情況

mysql> select count(user_id), avg(age) from user where name like '趙%' and mobile like '139%'G;  *************************** 1. row ***************************  count(user_id): 682      avg(age): 34.4296  1 row in set (7.03 sec)

執行耗時7.03秒

mysql> explain select count(user_id), avg(age) from user where name like '趙%' and mobile like '139%'G;  *************************** 1. row ***************************             id: 1    select_type: SIMPLE          table: user           type: ALL  possible_keys: NULL            key: NULL        key_len: NULL            ref: NULL           rows: 9928072          Extra: Using where  1 row in set (0.00 sec)

可以看到,查詢使用的是全表查詢,讀了所有的數據行。

4.2     單字段索引-name

首先在name字段創建一個單字段索引

mysql>ALTER TABLE `user` ADD INDEX `idx_user_name` (`name`) USING BTREE ;  Query OK, 0 rows affected (1 min 34.35 sec)  Records: 0  Duplicates: 0  Warnings: 0

執行SQL

mysql> select count(user_id), avg(age) from user where name like '趙%' and mobile like '139%'G;  *************************** 1. row ***************************  count(user_id): 682      avg(age): 34.4296  1 row in set (3.52 sec)

耗時3.52秒

mysql> explain select count(user_id), avg(age) from user where name like '趙%' and mobile like '139%'G;  *************************** 1. row ***************************             id: 1    select_type: SIMPLE          table: user           type: range  possible_keys: idx_user_name            key: idx_user_name        key_len: 98            ref: NULL           rows: 100634          Extra: Using index condition; Using where  1 row in set (0.00 sec)

使用索引進行檢索,讀取的數據減少到 10萬行。

4.3     單字段索引-mobile

為了測試方便,先刪除name字段的索引,再創建一個mobile字段索引

mysql> ALTER TABLE `user` DROP INDEX `idx_user_name`;  Query OK, 0 rows affected (0.05 sec)  Records: 0  Duplicates: 0  Warnings: 0    mysql>ALTER TABLE `user` ADD INDEX `idx_user_mobile` (`mobile`) USING BTREE ;  Query OK, 0 rows affected (1 min 27.50 sec)  Records: 0  Duplicates: 0  Warnings: 0

執行SQL

mysql> select count(user_id), avg(age) from user where name like '趙%' and mobile like '139%'G;  *************************** 1. row ***************************  count(user_id): 682        avg(age): 34.4296  1 row in set (9.93 sec)

耗時9.93秒

mysql> explain select count(user_id), avg(age) from user where name like '趙%' and mobile like '139%'G;  *************************** 1. row ***************************             id: 1    select_type: SIMPLE          table: user           type: range  possible_keys: idx_user_mobile            key: idx_user_mobile        key_len: 63            ref: NULL           rows: 233936          Extra: Using index condition; Using where  1 row in set (0.00 sec)

儘管我們的SQL語句將mobile字段作為第二個查詢條件,mysql仍然使用了mobile上的索引進行檢索。mobile索引過濾出來的數據有23萬行,比基於name的更多,所以耗時也就更長。

4.4     雙字段索引-name & mobile

這次我們將兩個字段建成一個聯合索引。

mysql> ALTER TABLE `user` DROP INDEX `idx_user_mobile`;  Query OK, 0 rows affected (0.07 sec)  Records: 0  Duplicates: 0  Warnings: 0    mysql> ALTER TABLE `user` ADD INDEX `idx_user_name_mobile` (`name`, `mobile`) USING BTREE ;  Query OK, 0 rows affected (1 min 54.81 sec)  Records: 0  Duplicates: 0  Warnings: 0

執行SQL

mysql> select avg(age) as age_avg from user where name like '趙%' and mobile like '139%'G;  *************************** 1. row ***************************  age_avg: 34.4296  1 row in set (0.06 sec)

執行時間大大縮短,只需要0.06秒

mysql> explain select avg(age) as age_avg from user where name like '趙%' and mobile like '139%'G;  *************************** 1. row ***************************             id: 1    select_type: SIMPLE          table: user           type: range  possible_keys: idx_user_name_mobile            key: idx_user_name_mobile        key_len: 161            ref: NULL           rows: 100764          Extra: Using index condition  1 row in set (0.00 sec)

讀取的行數還是10萬行,但時間大大縮短。從這個時間,我們應該能夠猜出mysql的過濾數據的過程。mysql執行where過濾時僅僅通過索引即可完成,然後根據索引中的user_id去數據頁面讀取相應的age值出來做平均。

4.5     終極版-覆蓋索引

前面的分析可以看到,為了計算平均值,mysql還需要讀取行數據。如果age字段也在這個索引中,查詢性能會進一步提升嗎?因為不再讀行數據。

調整索引

mysql> ALTER TABLE `user` DROP INDEX `idx_user_name_mobile`;  Query OK, 0 rows affected (0.06 sec)  Records: 0  Duplicates: 0  Warnings: 0    mysql> ALTER TABLE `user` ADD INDEX `idx_user_name_mobile_age` (`name`, `mobile`, `age`) USING BTREE ;  Query OK, 0 rows affected (1 min 55.32 sec)  Records: 0  Duplicates: 0  Warnings: 0

執行SQL

mysql> select avg(age) as age_avg from user where name like '趙%' and mobile like '139%'G;  *************************** 1. row ***************************  age_avg: 34.4296  1 row in set (0.04 sec)

執行時間更短,僅為0.04秒。數據量可能還不夠大,同上一個執行的區別不是太大。

mysql> explain select avg(age) as age_avg from user where name like '趙%' and mobile like '139%'G;  *************************** 1. row ***************************             id: 1    select_type: SIMPLE          table: user           type: range  possible_keys: idx_user_name_mobile_age            key: idx_user_name_mobile_age        key_len: 161            ref: NULL           rows: 103688          Extra: Using where; Using index  1 row in set (0.00 sec)

最重要的變化是Extra信息:Using index condition 變成 Using index。Using index condition 表示使用了索引作為查詢過濾的條件;Using index表示整個SQL只使用了索引。