昨天跟同事聊起数据表性能的问题,能不能仅用覆盖索引实现数据的汇总统计。找了一个开发环境已有的数据表进行测试,通过explain命令,能看到mysql通过覆盖索引就能实现sum的需求,而无须去读取实际行数据。

但开发环境数据量太小,对执行时间的优化,没有直观感受,于是决定做一个数据量能到千万级的数据表,方便测试。写个java程序来填充随机数据是第一选择,但还要动用IDE太麻烦,尝试直接使用mysql的函数来实现。

1     数据表设计

目的是演示如何生成千万级数据,只设计了一个最简单常用的数据表:user。

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

2     编写函数/过程

mysql的rand()函数,返回的是一个随机浮点数。为了实现随机插入数据,将基于这个函数实现。

2.1     获取随机整数

  1. CREATE FUNCTION `getRandomInt`(`maxValue` int) RETURNS int(11)
  2. BEGIN
  3. DECLARE randomInt int default 0;
  4. SET randomInt = FLOOR(rand() * `maxValue`);
  5. RETURN randomInt;
  6. END

2.2     获取随机字符串

  1. CREATE FUNCTION `getRandomString`(`length` int) RETURNS varchar(128) CHARSET utf8 COLLATE utf8_bin
  2. BEGIN
  3. DECLARE result VARCHAR(128) default '';
  4. DECLARE chars varchar(30) default 'abcdefghijklmnopqrstuvwxyz'; #全小写字母
  5. DECLARE charIndex int default 0;
  6. WHILE length > 0 DO
  7. SET charIndex = getRandomInt(26);
  8. SET result = concat(result, SUBSTRING(chars, charIndex + 1, 1));
  9. SET length = length - 1;
  10. END WHILE;
  11. RETURN result;
  12. END

2.3     获取随机手机号

11位手机号,必须1开始,后续10位只要是数字就行,有点不符合现在的手机号规则。

  1. CREATE FUNCTION `getRandomMobile`() RETURNS varchar(128) CHARSET utf8 COLLATE utf8_bin
  2. BEGIN
  3. DECLARE result VARCHAR(128) default '';
  4. DECLARE chars varchar(30) default '';
  5. DECLARE charIndex int default 0;
  6. DECLARE length int DEFAULT 10;
  7. WHILE length > 0 DO
  8. SET charIndex = getRandomInt(9);
  9. SET result = concat(result, SUBSTRING(chars, charIndex + 1, 1));
  10. SET length = length - 1;
  11. END WHILE;
  12. RETURN result;
  13. END

2.4     获取随机汉字

中文汉字的unicode,是从0X4E00(19968)开始的,写个函数随机从前2000个汉字中读出一个。这儿要注意的是char的方法,想生成汉字要使用 using utf16。实测生成的数据存入到 utf8 编码的数据表字段中,能正确显示。

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

2.5     获取随机姓名

姓名还不能完全使用随机汉字,“姓”我决定从百家姓里取前两百个。贴出来的代码中字符串不完整,感兴趣的自己上网查下来补一下就行。

  1. CREATE FUNCTION `getRandomChineseName`() RETURNS varchar(20) CHARSET utf8
  2. BEGIN
  3. DECLARE LAST_NAMES VARCHAR(300) DEFAULT '赵钱孙李周吴郑王...';
  4. DECLARE chineseName varchar(20) default '';
  5. SET chineseName = SUBSTRING(LAST_NAMES, getRandomInt(200) + 1, 1);
  6. SET chineseName = concat(chineseName, getRandomChineseChar());
  7. SET chineseName = concat(chineseName, getRandomChineseChar());
  8. RETURN chineseName;
  9. END

2.6     插入随机用户数据

在这个过程中实现真正插入用户数据。

  1. CREATE PROCEDURE `createRandomUser`(IN `count` int)
  2. BEGIN
  3. DECLARE userCount DECIMAL(10) default 0;
  4.  
  5. DECLARE account VARCHAR(32) DEFAULT '';
  6. DECLARE thePassword VARCHAR(128) DEFAULT '';
  7. DECLARE theName VARCHAR(32) DEFAULT '';
  8. DECLARE email VARCHAR(64) DEFAULT '';
  9. DECLARE mobile VARCHAR(20) DEFAULT '';
  10. DECLARE age int DEFAULT 0;
  11.  
  12. WHILE userCount < `count` DO
  13. SET account = getRandomString(10);
  14. SET thePassword = getRandomString(20);
  15. SET theName = getRandomChineseName();
  16. SET email = concat(account, '@codestory.tech');
  17. SET mobile = getRandomMobile();
  18. SET age = 10 + getRandomInt(50); #年龄10-60岁
  19.  
  20. insert into user values(null, account, thePassword, theName, email, mobile, age);
  21. SET userCount = userCount + 1;
  22. END WHILE;
  23. END 

3     生成数据

执行过程,就可以生成相应的数据。如下代码生成100行

  1. [SQL] call createRandomUser(100);
  2. 受影响的行: 100
  3. 时间: 1.004s

我电脑上这个表的数据行数

  1. mysql> select count(*) from user\G;
  2. *************************** 1. row ***************************
  3. count(*): 10001102
  4. 1 row in set (5.70 sec)

如下是我生成的部分数据

4     索引对查询性能的影响

设计一个简单的查询:所有赵姓用户且手机号139开头,平均年龄是多少?

测试SQL,以及查看执行情况

  1. select count(user_id), avg(age) from user where name like '赵%' and mobile like '139%'\G;
  2. explain select count(user_id), avg(age) from user where name like '赵%' and mobile like '139%'\G;

4.1     只有主键的情况

我们前面创建数据表时,只设置了主键,没有创建任何索引。这时候执行情况

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

执行耗时7.03秒

  1. mysql> explain select count(user_id), avg(age) from user where name like '赵%' and mobile like '139%'\G;
  2. *************************** 1. row ***************************
  3. id: 1
  4. select_type: SIMPLE
  5. table: user
  6. type: ALL
  7. possible_keys: NULL
  8. key: NULL
  9. key_len: NULL
  10. ref: NULL
  11. rows: 9928072
  12. Extra: Using where
  13. 1 row in set (0.00 sec)

可以看到,查询使用的是全表查询,读了所有的数据行。

4.2     单字段索引-name

首先在name字段创建一个单字段索引

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

执行SQL

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

耗时3.52秒

  1. mysql> explain select count(user_id), avg(age) from user where name like '赵%' and mobile like '139%'\G;
  2. *************************** 1. row ***************************
  3. id: 1
  4. select_type: SIMPLE
  5. table: user
  6. type: range
  7. possible_keys: idx_user_name
  8. key: idx_user_name
  9. key_len: 98
  10. ref: NULL
  11. rows: 100634
  12. Extra: Using index condition; Using where
  13. 1 row in set (0.00 sec)

使用索引进行检索,读取的数据减少到 10万行。

4.3     单字段索引-mobile

为了测试方便,先删除name字段的索引,再创建一个mobile字段索引

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

执行SQL

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

耗时9.93秒

  1. mysql> explain select count(user_id), avg(age) from user where name like '赵%' and mobile like '139%'\G;
  2. *************************** 1. row ***************************
  3. id: 1
  4. select_type: SIMPLE
  5. table: user
  6. type: range
  7. possible_keys: idx_user_mobile
  8. key: idx_user_mobile
  9. key_len: 63
  10. ref: NULL
  11. rows: 233936
  12. Extra: Using index condition; Using where
  13. 1 row in set (0.00 sec)

尽管我们的SQL语句将mobile字段作为第二个查询条件,mysql仍然使用了mobile上的索引进行检索。mobile索引过滤出来的数据有23万行,比基于name的更多,所以耗时也就更长。

4.4     双字段索引-name & mobile

这次我们将两个字段建成一个联合索引。

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

执行SQL

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

执行时间大大缩短,只需要0.06秒

  1. mysql> explain select avg(age) as age_avg from user where name like '赵%' and mobile like '139%'\G;
  2. *************************** 1. row ***************************
  3. id: 1
  4. select_type: SIMPLE
  5. table: user
  6. type: range
  7. possible_keys: idx_user_name_mobile
  8. key: idx_user_name_mobile
  9. key_len: 161
  10. ref: NULL
  11. rows: 100764
  12. Extra: Using index condition
  13. 1 row in set (0.00 sec)

读取的行数还是10万行,但时间大大缩短。从这个时间,我们应该能够猜出mysql的过滤数据的过程。mysql执行where过滤时仅仅通过索引即可完成,然后根据索引中的user_id去数据页面读取相应的age值出来做平均。

4.5     终极版-覆盖索引

前面的分析可以看到,为了计算平均值,mysql还需要读取行数据。如果age字段也在这个索引中,查询性能会进一步提升吗?因为不再读行数据。

调整索引

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

执行SQL

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

执行时间更短,仅为0.04秒。数据量可能还不够大,同上一个执行的区别不是太大。

  1. mysql> explain select avg(age) as age_avg from user where name like '赵%' and mobile like '139%'\G;
  2. *************************** 1. row ***************************
  3. id: 1
  4. select_type: SIMPLE
  5. table: user
  6. type: range
  7. possible_keys: idx_user_name_mobile_age
  8. key: idx_user_name_mobile_age
  9. key_len: 161
  10. ref: NULL
  11. rows: 103688
  12. Extra: Using where; Using index
  13. 1 row in set (0.00 sec)

最重要的变化是Extra信息:Using index condition 变成 Using index。Using index condition 表示使用了索引作为查询过滤的条件;Using index表示整个SQL只使用了索引。

制作mysql大数据表验证覆盖索引的更多相关文章

  1. Mysql大数据表优化处理

    原文链接: https://segmentfault.com/a/1190000006158186 当MySQL单表记录数过大时,增删改查性能都会急剧下降,可以参考以下步骤来优化: 单表优化 除非单表 ...

  2. mysql大数据表优化

    1.应尽量避免在 where 子句中使用!=或<>操作符,否则将引擎放弃使用索引而进行全表扫描. 2.对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by 涉 ...

  3. mysql大数据表删除操作锁表,导致其他线程等待锁超时(Lock wait timeout exceeded; try restarting transaction;)

    背景: 1.有一个定时任务,每10分钟入一批统计数据: 2.另一个定时任务,每天定时清理7天前数据,此定时任务每天01:18:00执行: 现象: 每天01:20:00的统计数据入库失败,异常信息如下, ...

  4. mysql大数据表改表结构方案

    有一个表有上千W数据, 用什么方法给这个表加一个字段最快?1. alert2. 建一个表和第一个表一样,只是多了要加的字段,然后用多个INSERT INTO SELECT语句limit写入3. 就是导 ...

  5. MySQL大数据表水平分区优化的详细步骤

    将运行中的大表修改为分区表 本文章代码仅限于以数据时间按月水平分区,其他需求可自行修改代码实现 1. 创建一张分区表 这张表的表字段和原表的字段一摸一样,附带分区 1 2 3 4 5 6 7 8 9 ...

  6. MySql数据表设计,索引优化,SQL优化,其他数据库

    MySql数据表设计,索引优化,SQL优化,其他数据库 1.数据表设计 1.1数据类型 1.2避免空值 1.3text类型优化 2.索引优化 2.1索引分类 2.2索引优化 3.SQL优化 3.1分批 ...

  7. MySQL大数据分页的优化思路和索引延迟关联

    之前上次在部门的分享会上,听了关于MySQL大数据的分页,即怎样使用limit offset,N来进行大数据的分页,现在做一个记录: 首先我们知道,limit offset,N的时候,MySQL的查询 ...

  8. MySQL中大数据表增加字段,增加索引实现

    MySQL中大数据表增加字段,通过增加索引实现 普通的添加字段sql ALTER TABLE `table_name` ADD COLUMN `num` int(10) NOT NULL DEFAUL ...

  9. mysql 大数据分页优化

    一.mysql大数据量使用limit分页,随着页码的增大,查询效率越低下. 1.   直接用limit start, count分页语句, 也是我程序中用的方法: select * from prod ...

随机推荐

  1. 讲解开源项目:功能强大的 JS 文件上传库

    本文作者:HelloGitHub-kalifun HelloGitHub 的<讲解开源项目>系列,项目地址:https://github.com/HelloGitHub-Team/Arti ...

  2. mybatis 源码分析(四)一二级缓存分析

    本篇博客主要讲了 mybatis 一二级缓存的构成,以及一些容易出错地方的示例分析: 一.mybatis 缓存体系 mybatis 的一二级缓存体系大致如下: 首先当一二级缓存同时开启的时候,首先命中 ...

  3. Windows上IDEA搭建最新Spark2.4.3源码调试的开发环境

    相信很多同学都想通过阅读一些框架的源码,来提高自己的代码能力,但往往在第一步,搭建环境的时候就碰了壁. 本篇就来介绍下如何在Windows下,将最新版的Spark2.4.3编译,并导入到IDEA编译器 ...

  4. ionic $ioniActionSheet 在安卓手机没样式

    解决方法: 添加以下修复css样式 /** * Action Sheets for Android * ------------------------------------------------ ...

  5. ElasticSearch:组合查询或复合查询

    Bool查询 允许在单独的查询中组合任意数量的查询,指定的查询语句表名哪些部分是必须匹配(must).应该匹配(should)或不能匹配(must_not) Bool过滤器 和查询功能一致,但是同等情 ...

  6. ‎CocosBuilder 学习笔记(2) .ccbi 文件结构分析

    ccbi总体结构 CCBReader按字节读取.ccbi内容,每个字节8位二进制. .ccbi总体结构分为4个部分: Header 第0-3字节:ibcc .ccbi文件的标志.readHeader方 ...

  7. 前端开发-CSS语法标准

    一.命名规则说明: 1.命名规则说明: 所有的命名最好都小写 属性的值一定要用双引号("")括起来,且一定要有值如class="nav",id="na ...

  8. SpringBoot 2 快速整合 | 统一异常处理

    统一异常处理相关注解介绍 @ControllerAdvice 声明在类上用于指定该类为控制增强器类,如果想声明返回的结果为 RESTFull 风格的数据,需要在声明 @ExceptionHandler ...

  9. c++并查集配合STL MAP的实现(洛谷P2814题解)

    不会并查集的话请将此文与我以前写的并查集一同食用. 原题来自洛谷 原题 文字稿在此: 题目背景 现代的人对于本家族血统越来越感兴趣. 题目描述 给出充足的父子关系,请你编写程序找到某个人的最早的祖先. ...

  10. NLP(十一) 提取文本摘要

    gensim.summarization库的函数 gensim.summarization.summarize(text, ratio=0.2, word_count=None, split=Fals ...