一,索引的重要性

索引用于快速找出在某个列中有一特定值的行。不使用索引,MySQL必须从第1条记录开始然后读完整个表直到找出相关的行。表越大,花费的时间越多。如果表中查询的列有一个索引,MySQL能快速到达一个位置去搜寻到数据文件的中间,没有必要看所有数据。注意如果你需要访问大部分行,顺序读取要快得多,因为此时我们避免磁盘搜索。

假如你用新华字典来查找“”这个汉字,不使用目录的话,你可能要从新华字典的第一页找到最后一页,可能要花二个小时。字典越厚呢,你花的时间就越多。现在你使用目录来查找“”这个汉字,张的首字母是zz开头的汉字从900多页开始,有了这条线索,你查找一个汉字可能只要一分钟,由此可见索引的重要性。但是索引建的是不是越多越好呢,当然不是,如果一本书的目录分成好几级的话,我想你也会晕的。

二,准备工作

  1. //准备二张测试表
  2. mysql> CREATE TABLE `test_t` (
  3. ->   `id` int(11) NOT NULL auto_increment,
  4. ->   `num` int(11) NOT NULL default '0',
  5. ->   `d_num` varchar(30) NOT NULL default '0',
  6. ->   PRIMARY KEY  (`id`)
  7. -> ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
  8. Query OK, 0 rows affected (0.05 sec)
  9. mysql> CREATE TABLE `test_test` (
  10. ->   `id` int(11) NOT NULL auto_increment,
  11. ->   `num` int(11) NOT NULL default '0',
  12. ->   PRIMARY KEY  (`id`)
  13. -> ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
  14. Query OK, 0 rows affected (0.05 sec)
  15. //创建一个存储过程,为插数据方便
  16. mysql> delimiter |
  17. mysql> create procedure i_test(pa int(11),tab varchar(30))
  18. -> begin
  19. ->     declare max_num int(11) default 100000;
  20. ->     declare i int default 0;
  21. ->     declare rand_num int;
  22. ->  declare double_num char;
  23. ->
  24. ->  if tab != 'test_test' then
  25. ->         select count(id) into max_num from test_t;
  26. ->         while i < pa do
  27. ->             if max_num < 100000 then
  28. ->                 select cast(rand()*100 as unsigned) into rand_num;
  29. ->                 select concat(rand_num,rand_num) into double_num;
  30. ->                 insert into test_t(num,d_num)values(rand_num,double_num);
  31. ->             end if;
  32. ->             set i = i +1;
  33. ->         end while;
  34. ->  else
  35. ->         select count(id) into max_num from test_test;
  36. ->         while i < pa do
  37. ->             if max_num < 100000 then
  38. ->                 select cast(rand()*100 as unsigned) into rand_num;
  39. ->                 insert into test_test(num)values(rand_num);
  40. ->             end if;
  41. ->             set i = i +1;
  42. ->         end while;
  43. ->  end if;
  44. -> end|
  45. Query OK, 0 rows affected (0.00 sec)
  46. mysql> delimiter ;
  47. mysql> show variables like "%pro%";   //查看一下,记录执行的profiling是不是开启动了,默认是不开启的
  48. +---------------------------+-------+
  49. | Variable_name             | Value |
  50. +---------------------------+-------+
  51. | profiling                 | OFF   |
  52. | profiling_history_size    | 15    |
  53. | protocol_version          | 10    |
  54. | slave_compressed_protocol | OFF   |
  55. +---------------------------+-------+
  56. 4 rows in set (0.00 sec)
  57. mysql> set profiling=1;           //开启后,是为了对比加了索引后的执行时间
  58. Query OK, 0 rows affected (0.00 sec)
//准备二张测试表 mysql> CREATE TABLE `test_t` (  ->   `id` int(11) NOT NULL auto_increment,  ->   `num` int(11) NOT NULL default '0',  ->   `d_num` varchar(30) NOT NULL default '0',  ->   PRIMARY KEY  (`id`)  -> ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; Query OK, 0 rows affected (0.05 sec)  mysql> CREATE TABLE `test_test` (  ->   `id` int(11) NOT NULL auto_increment,  ->   `num` int(11) NOT NULL default '0',  ->   PRIMARY KEY  (`id`)  -> ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; Query OK, 0 rows affected (0.05 sec)    //创建一个存储过程,为插数据方便 mysql> delimiter | mysql> create procedure i_test(pa int(11),tab varchar(30))  -> begin  ->     declare max_num int(11) default 100000;  ->     declare i int default 0;  ->     declare rand_num int;  ->  declare double_num char;  ->  ->  if tab != 'test_test' then  ->         select count(id) into max_num from test_t;  ->         while i < pa do  ->             if max_num < 100000 then  ->                 select cast(rand()*100 as unsigned) into rand_num;  ->                 select concat(rand_num,rand_num) into double_num;  ->                 insert into test_t(num,d_num)values(rand_num,double_num);  ->             end if;  ->             set i = i +1;  ->         end while;  ->  else  ->         select count(id) into max_num from test_test;  ->         while i < pa do  ->             if max_num < 100000 then  ->                 select cast(rand()*100 as unsigned) into rand_num;  ->                 insert into test_test(num)values(rand_num);  ->             end if;  ->             set i = i +1;  ->         end while;  ->  end if;  -> end| Query OK, 0 rows affected (0.00 sec)  mysql> delimiter ; mysql> show variables like "%pro%";   //查看一下,记录执行的profiling是不是开启动了,默认是不开启的 +---------------------------+-------+ | Variable_name             | Value | +---------------------------+-------+ | profiling                 | OFF   | | profiling_history_size    | 15    | | protocol_version          | 10    | | slave_compressed_protocol | OFF   | +---------------------------+-------+ 4 rows in set (0.00 sec)    mysql> set profiling=1;           //开启后,是为了对比加了索引后的执行时间 Query OK, 0 rows affected (0.00 sec) 

三,实例

1,单表数据太少,索引反而会影响速度

  1. mysql> call i_test(10,'test_t');    //向test_t表插入10条件
  2. Query OK, 1 row affected (0.02 sec)
  3. mysql> select num from test_t where num!=0;
  4. mysql> explain select num from test_t where num!=0\G;
  5. *************************** 1. row ***************************
  6. id: 1
  7. select_type: SIMPLE
  8. table: test_t
  9. type: ALL
  10. possible_keys: NULL
  11. key: NULL
  12. key_len: NULL
  13. ref: NULL
  14. rows: 10
  15. Extra: Using where
  16. 1 row in set (0.00 sec)
  17. ERROR:
  18. No query specified
  19. mysql> create index num_2 on test_t (num);
  20. Query OK, 10 rows affected (0.19 sec)
  21. Records: 10  Duplicates: 0  Warnings: 0
  22. mysql> select num from test_t where num!=0;
  23. mysql> explain select num from test_t where num!=0\G;
  24. *************************** 1. row ***************************
  25. id: 1
  26. select_type: SIMPLE
  27. table: test_t
  28. type: index
  29. possible_keys: num_2
  30. key: num_2
  31. key_len: 4
  32. ref: NULL
  33. rows: 10
  34. Extra: Using where; Using index
  35. 1 row in set (0.00 sec)
  36. ERROR:
  37. No query specified
  38. mysql> show profiles;
  39. +----------+------------+---------------------------------------------+
  40. | Query_ID | Duration   | Query                                       |
  41. +----------+------------+---------------------------------------------+
  42. |        1 | 0.00286325 | call i_test(10,'test_t')                    |    //插入十条数据
  43. |        2 | 0.00026350 | select num from test_t where num!=0         |
  44. |        3 | 0.00022250 | explain select num from test_t where num!=0 |
  45. |        4 | 0.18385400 | create index num_2 on test_t (num)          |    //创建索引
  46. |        5 | 0.00127525 | select num from test_t where num!=0         |    //使用索引后,差不多是没有使用索引的0.2倍
  47. |        6 | 0.00024375 | explain select num from test_t where num!=0 |
  48. +----------+------------+---------------------------------------------+
  49. 6 rows in set (0.00 sec)
mysql> call i_test(10,'test_t');    //向test_t表插入10条件 Query OK, 1 row affected (0.02 sec)  mysql> select num from test_t where num!=0; mysql> explain select num from test_t where num!=0\G; *************************** 1. row ***************************  id: 1  select_type: SIMPLE  table: test_t  type: ALL  possible_keys: NULL  key: NULL  key_len: NULL  ref: NULL  rows: 10  Extra: Using where 1 row in set (0.00 sec)  ERROR: No query specified  mysql> create index num_2 on test_t (num); Query OK, 10 rows affected (0.19 sec) Records: 10  Duplicates: 0  Warnings: 0  mysql> select num from test_t where num!=0;  mysql> explain select num from test_t where num!=0\G; *************************** 1. row ***************************  id: 1  select_type: SIMPLE  table: test_t  type: index  possible_keys: num_2  key: num_2  key_len: 4  ref: NULL  rows: 10  Extra: Using where; Using index 1 row in set (0.00 sec)  ERROR: No query specified  mysql> show profiles; +----------+------------+---------------------------------------------+ | Query_ID | Duration   | Query                                       | +----------+------------+---------------------------------------------+ |        1 | 0.00286325 | call i_test(10,'test_t')                    |    //插入十条数据 |        2 | 0.00026350 | select num from test_t where num!=0         | |        3 | 0.00022250 | explain select num from test_t where num!=0 | |        4 | 0.18385400 | create index num_2 on test_t (num)          |    //创建索引 |        5 | 0.00127525 | select num from test_t where num!=0         |    //使用索引后,差不多是没有使用索引的0.2倍 |        6 | 0.00024375 | explain select num from test_t where num!=0 | +----------+------------+---------------------------------------------+ 6 rows in set (0.00 sec)

解释:

id:表示sql执行的顺序

select_type:SIMPLE,PRIMARY,UNION,DEPENDENT UNION,UNION RESULT,SUBQUERY,DEPENDENT SUBQUERY,DERIVED不同的查询语句会有不同的select_type

table:表示查找的表名

type:表示使用索引类型,或者有无使用索引.效率从高到低const、eq_reg、ref、range、index和ALL,其实这个根你sql的写法有直接关系,例如:能用主键就用主键,where后面的条件加上索引,如果是唯一加上唯一索引等

possible_keys:可能存在的索引

key:使用索引

key_len:使用索引的长度

ref:使用哪个列或常数与key一起从表中选择行,一般在多表联合查询时会有。

rows:查找出的行数

Extra:额外说明

前段时间写过一篇博文mysql distinct和group by谁更好,里面有朋友留言,说测试结果根我当时做的测试结果不一样,当时我打比方解释了一下,今天有时间,以例子的形势,更直观的表达出索引的工作原理。

2,where后的条件,order by ,group by 等这样过滤时,后面的字段最好加上索引。根据实际情况,选择PRIMARY KEY、UNIQUE、INDEX等索引,但是不是越多越好,要适度。

3,联合查询,子查询等多表操作时关连字段要加索引

  1. mysql> call i_test(10,'test_test');    //向test_test表插入10条数据
  2. Query OK, 1 row affected (0.02 sec)
  3. mysql> explain select a.num as num1,b.num as num2 from test_t as a left join tes
  4. t_test as b on a.num=b.num\G;
  5. *************************** 1. row ***************************
  6. id: 1
  7. select_type: SIMPLE
  8. table: a
  9. type: index
  10. possible_keys: NULL
  11. key: num_2
  12. key_len: 4
  13. ref: NULL
  14. rows: 10
  15. Extra: Using index
  16. *************************** 2. row ***************************
  17. id: 1
  18. select_type: SIMPLE
  19. table: b
  20. type: ref
  21. possible_keys: num_1
  22. key: num_1
  23. key_len: 4
  24. ref: bak_test.a.num   //bak_test是数据库名,a.num是test_t的一个字段
  25. rows: 1080
  26. Extra: Using index
  27. 2 rows in set (0.01 sec)
  28. ERROR:
  29. No query specified
mysql> call i_test(10,'test_test');    //向test_test表插入10条数据 Query OK, 1 row affected (0.02 sec)  mysql> explain select a.num as num1,b.num as num2 from test_t as a left join tes t_test as b on a.num=b.num\G; *************************** 1. row ***************************  id: 1  select_type: SIMPLE  table: a  type: index  possible_keys: NULL  key: num_2  key_len: 4  ref: NULL  rows: 10  Extra: Using index *************************** 2. row ***************************  id: 1  select_type: SIMPLE  table: b  type: ref  possible_keys: num_1  key: num_1  key_len: 4  ref: bak_test.a.num   //bak_test是数据库名,a.num是test_t的一个字段  rows: 1080  Extra: Using index 2 rows in set (0.01 sec)  ERROR: No query specified

数据量特别大的时候,最好不要用联合查询,即使你做了索引。

上面只是个人的一点小结,抛砖引玉一下。

转载请注明
作者:海底苍鹰
地址:http://blog.51yip.com/mysql/1157.html

[转]添加mysql索引的3条原则相关推荐

  1. mysql索引最左前缀原则

    mysql索引最左前缀原则 创建索引可以大大提高系统的性能. 第一,通过创建唯一性索引,可以保证数据库表中每一行数据的唯一性. 第二,可以大大加快数据的检索速度,这也是创建索引的最主要的原因. 第三, ...

  2. 深入理解MySQL索引设计和优化原则

    索引类型 探讨索引设计和优化原则之前,先给大家熟悉一下索引类型: 主键索引PRIMARY KEY:它是一种特殊的唯一索引,不允许有空值.一般是在建表的时候同时创建主键索引. 唯一索引UNIQUE:唯一 ...

  3. MySQL索引之最左匹配原则

    简介 这篇文章的初衷是很多文章都告诉你最左匹配原则,却没有告诉你,实际场景下它到底是如何工作的,本文就是为了阐述清这个问题. 准备 为了方面后续的说明,我们首先建立一个如下的表(MySQL5.7),表 ...

  4. MySql 索引的最左匹配原则举例详解

    最左匹配原则 最左匹配原则就是指在联合索引中,如果你的 SQL 语句中用到了联合索引中的最左边的索引,那么这条 SQL 语句就可以利用这个联合索引去进行匹配. 例如某表现有索引(a,b,c),现在你有 ...

  5. MySQL索引原理,设计原则

  6. MySQL 索引最左匹配原则

    csdn原文:http://blog.csdn.net/zhu19774279/article/details/46473981 本文的原文地址在此:https://www.percona.com/b ...

  7. MySQL索引与查询优化

    目录 About MySQL Why MySQL MySQL Index Why Index 索引是如何工作的 如何使用 创建索引 查看索引 删除索引 索引的使用原则 写操作比较频繁的列慎重加索引 索 ...

  8. MySQL索引与Index Condition Pushdown(二)

    实验 先从一个简单的实验开始直观认识ICP的作用. 安装数据库 首先需要安装一个支持ICP的MariaDB或MySQL数据库.我使用的是MariaDB 5.5.34,如果是使用MySQL则需要5.6版 ...

  9. 关于MySQL索引面试题的6连炮!招架的住吗?

    往期热门文章: 1.<往期精选优秀博文都在这里了!> 2.真香!IDEA 最新版本,支持免打扰和轻量模式! 3.微服务如何防止雪崩?阿里开源之Sentinel限流.熔断来帮你! 4.为什么 ...

最新文章

  1. 云服务器基础运维与管理
  2. jquery json 判断用户是否已注册
  3. vue 输入框限制3位小数_vue+element 中 el-input框 限制 只能输入数字及几位小数(自定义)和输入框之键盘...
  4. python编程软件p-Python编程工具pycharm的使用
  5. jquery 使用animate来改变高度自动添加样式overflow:hidden的问题
  6. 如何更改电脑ip地址租期_局域网通过IP地址如何找到电脑的位置
  7. spark学习-33-Spark安全机制SecurityManager
  8. maven学习- 私服nexus搭建
  9. 【蓝牙】设备管理器找不到蓝牙
  10. 流传甚少的seo排名爆破技术全解析
  11. 计算机网络的应用领域有那些,计算机网络应用领域
  12. Ubuntu垃圾箱目录及清空
  13. 微云html网页,微云收藏在哪里_以及腾讯微云收藏网页版怎么用? - 软件教程 - 格子啦...
  14. 《疯狂原始人》温馨而搞笑片段截图
  15. 传真百科:电子邮件能取代传真吗
  16. macOS更新10.14.6 更新到macOS Monterey
  17. SpringBoot+Vue实现前后端分离教学评价系统
  18. 美通企业日报 | 阿迪达斯和碧昂丝达成标志性合作;万豪国际公布亚太区2020年发展愿景...
  19. git clone时提示,git remote: HTTP Basic: Access denied 错误
  20. 近一年多看过的电影和书籍

热门文章

  1. SqlServer英文单词全字匹配
  2. information_schema.triggers 学习
  3. cookie存放位置
  4. Codility算法测验(三)
  5. 【OfficeDIY】有了站点了 ^_^
  6. Linux虚拟文件系统简介
  7. 前序遍历与中序遍历确定后序遍历
  8. 通过WebViewJavascriptBridge实现OC与JS交互
  9. WINDOWS和LINUX下带时间的PING包监控脚本
  10. 狂宴终有尽时,留一份清醒一份醉 比特币现金BCH凸显投资价值