MySQL 索引管理 ---基础调优,优化查询

 

索引就好比一本书的目录,它会让你更快的找到内容

让获取的数据更有目的性,从而提高数据库检索数据的性能。

 

索引建立在表的列上(字段)的。

在where后面的列建立索引才会加快查询速度。

pages<---索引(属性)<----查数据。

索引分类:

主键(约束)索引:列中的值必须是唯一的并且非空的

普通索引:随便什么列  *****

唯一(约束)索引:列中的值必须是唯一的

-----------------------

索引创建和删除:

use world;

create table test select * from city;

创建索引

alter table test add index idx_name(name);

查询索引

desc test;

show index from test\\G

删除索引

alter table test drop index idx_name;

-----------------------

1、主键索引:只能有一个主键。

       主键索引:列的内容是唯一值,高中学号.

       表创建的时候至少要有一个主键索引,最好和业务无关。

---主键索引创建     

1.1.建立表时

CREATE TABLE `test` (

  `id` int(4) NOT NULL AUTO_INCREMENT,

  `name` char(20) NOT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=UTF8;

 

1.2.建立表后增加

CREATE TABLE `test1` (

  `id` int(4) NOT NULL,

  `name` char(20) NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=UTF8;

增加自增主键

alter table test1 change id id int(11) primary key not null auto_increment;

-------------------   

2、普通索引

       加快查询速度,工作中优化数据库的关键。

       在合适的列上建立索引,让数据查询更高效。

       create index index_name on test(name);

       alter table test add index index_name(name);

       用了索引,查一堆内容。

       在where条件关键字后面的列建立索引才会加快查询速度.

       select id,name from test where state=1 order by id group by name;

-------------------   

3、唯一索引

内容唯一,但不是主键。

alter table test add unique index idx_name(name);

怎么判断某个列的值都是唯一的?

1、总行数查询

select count(*) from test;

2、基于某个列去重复之后还剩多少行

select count(distinct population) from test;

-------------------

---前缀索引和联合索引

1、前缀索引:

根据字段的前N个字符建立索引

alter table test add index idx_name(name(10)); 

 

联合索引:多个字段建立一个索引。

where a女生 and b身高165 and c身材好

index(a,b,c)

特点:前缀生效特性。

a,ab,abc,ac  可以走索引或部分走索引。

b  bc c  ca  ba  不走索引。

------------------------

原则:把最常用来作为条件查询的列放在前面。

 

create table people(id int not null auto_increment primary key ,

name varchar(20),gender enum(\'m\',\'f\'),shengao int,tizhong int);

alter table people add index idx_gst(gender,shengao,tizhong);

-----------

alter table xx  add index xxx()

alter table xxx drop index xxx

desc xxx

show index from xxx

-----------

 

----explain命令的应用

 

mysql> explain select id,name from test where name=\'oldboy\'\\G

*************************** 1. row ***************************

           id: 1

  select_type: SIMPLE

        table: test

         type: ref

possible_keys: ind_name

          key: ind_name

      key_len: 60

          ref: const

         rows: 1

        Extra: Using where; Using index

1 row in set (0.00 sec)

++++++++++++++++++++++++++++

explain  select SQL_NO_CACHE  * from test where name=\'oldboy\'\\G

SQL_NO_CACHE的作用是禁止缓存查询结果。

explain select name,gender,age from test where gender=\'F\' and age <20;

------

在MySQL中,查询数据总共两种方式:全表扫描、索引扫描           ***************

通过explain命令的type可以看到,ALL的话就是全表扫描

mysql在使用全表扫描时的性能是极其差的,所以MySQL尽量避免出现全表扫描

全表扫描什么时候出现?

1、业务确实要获取所有数据

2、不走索引,导致的全表扫描

    2.1 没索引

    2.2 索引创建有问题

    2.3 语句有问题

索引扫描有很多种级别,也是通过explain type能看到

--------------------------

type : 表示MySQL在表中找到所需行的方式,又称“访问类型”

常见类型如下:

index<range<ref<eq_ref<const<system<Null

从左到右,性能从最差到最好,我们认为至少要达到range级别

1、index:Full Index Scan,index与ALL区别为index类型只遍历索引树

2、range:索引范围扫描,对索引的扫描开始于某一点,返回匹配值域的行。

显而易见的索引范围扫描是带有between或者where子句里带有<,>查询

alter table test add index idx_popu(population);

explain select * from test where population >5000000;

当mysql使用索引去查找一系列值时,例如IN()和OR列表,也会显示range(范围扫描),当然性能上面是有差异的。

explain select * from test where countrycode in (\'chn\',\'jpn\');    --等于某个值  不用做全表扫描

改写为:

explain select * from test where countrycode=\'chn\'

union

select * from test where countrycode=\'jpn\';

3、ref:使用非唯一索引扫描或者唯一索引的前缀扫描,返回匹配某个单独值的记录行

explain select * from test where countrycode=\'chn\';

4、eq_ref:类似ref,区别就在使用的索引是唯一索引,对于每个索引键值,表中只有一条记录匹配,简单来说,

就是多表连接中使用primary key或者 unique key作为关联条件

5、const、system:当MySQL对查询某部分进行优化,并转换为一个常量时,使用这些类型访问。

如将主键置于where列表中,MySQL就能将该查询转换为一个常量

6、NULL:MySQL在优化过程中分解语句,执行时甚至不用访问表或索引,

         例如从一个索引列里选取最小值可以通过单独索引查找完成。

 

mysql> explain select name,population from city;

+----+-------------+-------+------+---------------+------+---------+------+------+-------+

| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows | Extra |

+----+-------------+-------+------+---------------+------+---------+------+------+-------+

|  1 | SIMPLE      | city  | ALL  | NULL          | NULL | NULL    | NULL | 4188 | NULL  |

+----+-------------+-------+------+---------------+------+---------+------+------+-------+     

Extra:

Using temporary

Using filesort

Using join buffer

如果出现以上附加信息:

请检查order by  ,group by ,distinct,join 条件列上没有索引

explain select * from city where countrycode=\'CHN\' order by population;

--------------------------------------

--------建立索引的原则(运维规范)

select count(distinct user) from mysql.user;

select count(distinct user,host) from mysql.user;

一、数据库索引的设计原则:

      为了使索引的使用效率更高,在创建索引时,必须考虑在哪些字段上创建索引和创建什么类型的索引。

那么索引设计原则又是怎样的?

 

1.选择唯一性索引          

       唯一性索引的值是唯一的,可以更快速的通过该索引来确定某条记录。

例如,学生表中学号是具有唯一性的字段。为该字段建立唯一性索引可以很快的确定某个学生的信息。

如果使用姓名的话,可能存在同名现象,从而降低查询速度。

 

主键索引和唯一键索引,在查询中使用是效率最高的。           *********************

 

2.为经常需要排序、分组和联合操作的字段建立索引         ******************

经常需要ORDER BY、GROUP BY、DISTINCT和UNION等操作的字段,排序操作会浪费很多时间。

如果为其建立索引,可以有效地避免排序操作。

 

3.为常作为查询条件的字段建立索引           *******************

如果某个字段经常用来做查询条件,那么该字段的查询速度会影响整个表的查询速度。因此,

为这样的字段建立索引,可以提高整个表的查询速度。

    3.1  经常查询

    3.2  列值的重复值少

select count(*) from mysql.user;   

select count(distinct user) from mysql.user;

select count(distinct user,host) from mysql.user;

注:如果经常作为条件的列,重复值特别多,可以建立联合索引。

4.尽量使用前缀来索引                       *****************

如果索引字段的值很长,最好使用值的前缀来索引。例如,TEXT和BLOG类型的字段,进行全文检索

会很浪费时间。如果只检索字段的前面的若干个字符,这样可以提高检索速度。

 

------------------------以上的是重点关注的,以下是能保证则保证的--------------------

5.限制索引的数目

索引的数目不是越多越好。每个索引都需要占用磁盘空间,索引越多,需要的磁盘空间就越大。

修改表时,对索引的重构和更新很麻烦。越多的索引,会使更新表变得很浪费时间。

6.尽量使用数据量少的索引          **************

如果索引的值很长,那么查询的速度会受到影响。例如,对一个CHAR(100)类型的字段进行全文

检索需要的时间肯定要比对CHAR(10)类型的字段需要的时间要多。

8.删除不再使用或者很少使用的索引      

表中的数据被大量更新,或者数据的使用方式被改变后,原有的一些索引可能不再需要。数据库管理

员应当定期找出这些索引,将它们删除,从而减少索引对更新操作的影响。

--------不走索引的情况(开发规范)

 

重点关注:

1) 没有查询条件,或者查询条件没有建立索引

select * from tab;   全表扫描。

select  * from tab where 1=1;

在业务数据库中,特别是数据量比较大的表。

是没有全表扫描这种需求。

1、对用户查看是非常痛苦的。

2、对服务器来讲毁灭性的。

 

(1)select * from tab;

SQL改写成以下语句:

selec  * from tab  order by  price  limit 10      需要在price列上建立索引

(2)

select  * from  tab where name=\'zhangsan\'          name列没有索引

改:

       1、换成有索引的列作为查询条件

       2、将name列建立索引

2) 查询结果集是原表中的大部分数据,应该是30%以上。

查询的结果集,超过了总数行数30%,优化器觉得就没有必要走索引了。

假如:tab表 id,name    id:1-100w  ,id列有索引

select * from tab  where id>500000;

如果业务允许,可以使用limit控制。

怎么改写 ?

结合业务判断,有没有更好的方式。如果没有更好的改写方案

尽量不要在mysql存放这个数据了。放到redis里面。

3) 索引本身失效,统计数据不真实

索引有自我维护的能力。

对于表内容变化比较频繁的情况下,有可能会出现索引失效。

4) 查询条件使用函数在索引列上,或者对索引列进行运算,运算包括(+,-,*,/,! 等)

例子:

错误的例子:select * from test where id-1=9;

正确的例子:select * from test where id=10;

5)隐式转换导致索引失效.这一点应当引起重视.也是开发中经常会犯的错误.

由于表的字段tu_mdn定义为varchar2(20),但在查询时把该字段作为number类型以where条件传给数据库,

这样会导致索引失效.

错误的例子:select * from test where tu_mdn=13333333333;      数据类型必须和表中的数据类型一致       ******************

正确的例子:select * from test where tu_mdn=\'13333333333\';

------------------------

mysql> alter table tab add index inx_tel(telnum);

Query OK, 0 rows affected (0.03 sec)

Records: 0  Duplicates: 0  Warnings: 0

mysql> desc tab;

+--------+-------------+------+-----+---------+-------+

| Field  | Type        | Null | Key | Default | Extra |

+--------+-------------+------+-----+---------+-------+

| id     | int(11)     | YES  |     | NULL    |       |

| name   | varchar(20) | YES  |     | NULL    |       |

| telnum | varchar(20) | YES  | MUL | NULL    |       |

+--------+-------------+------+-----+---------+-------+

3 rows in set (0.01 sec)

mysql> select * from tab where telnum=\'1333333\';

+------+------+---------+

| id   | name | telnum  |

+------+------+---------+

|    1 | a    | 1333333 |

+------+------+---------+

1 row in set (0.00 sec)

mysql> select * from tab where telnum=1333333;

+------+------+---------+

| id   | name | telnum  |

+------+------+---------+

|    1 | a    | 1333333 |

+------+------+---------+

1 row in set (0.00 sec)

mysql> explain  select * from tab where telnum=\'1333333\';

+----+-------------+-------+------+---------------+---------+---------+-------+------+-----------------------+

| id | select_type | table | type | possible_keys | key     | key_len | ref   | rows | Extra                 |

+----+-------------+-------+------+---------------+---------+---------+-------+------+-----------------------+

|  1 | SIMPLE      | tab   | ref  | inx_tel       | inx_tel | 63      | const |    1 | Using index condition |

+----+-------------+-------+------+---------------+---------+---------+-------+------+-----------------------+

1 row in set (0.00 sec)

mysql> explain  select * from tab where telnum=1333333;

+----+-------------+-------+------+---------------+------+---------+------+------+-------------+

| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows | Extra       |

+----+-------------+-------+------+---------------+------+---------+------+------+-------------+

|  1 | SIMPLE      | tab   | ALL  | inx_tel       | NULL | NULL    | NULL |    2 | Using where |

+----+-------------+-------+------+---------------+------+---------+------+------+-------------+

1 row in set (0.00 sec)

mysql> explain  select * from tab where telnum=1555555;

+----+-------------+-------+------+---------------+------+---------+------+------+-------------+

| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows | Extra       |

+----+-------------+-------+------+---------------+------+---------+------+------+-------------+

|  1 | SIMPLE      | tab   | ALL  | inx_tel       | NULL | NULL    | NULL |    2 | Using where |

+----+-------------+-------+------+---------------+------+---------+------+------+-------------+

1 row in set (0.00 sec)

mysql> explain  select * from tab where telnum=\'1555555\';

+----+-------------+-------+------+---------------+---------+---------+-------+------+-----------------------+

| id | select_type | table | type | possible_keys | key     | key_len | ref   | rows | Extra                 |

+----+-------------+-------+------+---------------+---------+---------+-------+------+-----------------------+

|  1 | SIMPLE      | tab   | ref  | inx_tel       | inx_tel | 63      | const |    1 | Using index condition |

+----+-------------+-------+------+---------------+---------+---------+-------+------+-----------------------+

1 row in set (0.00 sec)

-----------------------

6) <>  ,not in 不走索引      一般不推荐使用           *****************

EXPLAIN SELECT * FROM teltab WHERE telnum   <> \'110\';

EXPLAIN  SELECT * FROM teltab WHERE telnum  NOT IN (\'110\',\'119\');

------------------------------------

mysql> select * from tab where telnum <> \'1555555\';

+------+------+---------+

| id   | name | telnum  |

+------+------+---------+

|    1 | a    | 1333333 |

+------+------+---------+

1 row in set (0.00 sec)

mysql> explain select * from tab where telnum <> \'1555555\';

-------------------------------------

单独的>,<,in 有可能走,也有可能不走,和结果集有关,尽量结合业务添加limit

or或in  尽量改成union

EXPLAIN  SELECT * FROM teltab WHERE telnum   IN (\'110\',\'119\');

改写成:

EXPLAIN SELECT * FROM teltab WHERE telnum=\'110\'

UNION ALL

SELECT * FROM teltab WHERE telnum=\'119\'

-----------------------------------

7)   like \"%_\" 百分号在最前面不走

EXPLAIN SELECT * FROM teltab WHERE telnum LIKE \'31%\'   走range索引扫描

EXPLAIN SELECT * FROM teltab WHERE telnum LIKE \'%110\'  不走索引

%linux%类的搜索需求,可以使用elasticsearch

 

8) 单独引用复合索引里非第一位置的索引列.

列子:

复合索引:

DROP TABLE t1

CREATE TABLE t1 (id INT,NAME VARCHAR(20),age INT ,sex ENUM(\'m\',\'f\'),money INT);

ALTER TABLE t1 ADD INDEX t1_idx(money,age,sex);

DESC t1

SHOW INDEX FROM t1

走索引的情况测试:

EXPLAIN SELECT NAME,age,sex,money FROM t1 WHERE money=30 AND age=30  AND sex=\'m\';

EXPLAIN SELECT NAME,age,sex,money FROM t1 WHERE money=30 AND age=30  ;

EXPLAIN SELECT NAME,age,sex,money FROM t1 WHERE money=30  AND sex=\'m\';    ----->部分走索引

不走索引的:

EXPLAIN SELECT  NAME,age,sex,money FROM t1 WHERE  age=20

EXPLAIN SELECT NAME,age,sex,money FROM t1 WHERE  age=30  AND sex=\'m\';

EXPLAIN SELECT NAME,age,sex,money FROM t1 WHERE   sex=\'m\';

收藏 打印