当前位置:Gxlcms > 数据库问题 > MySQL 索引管理与执行计划

MySQL 索引管理与执行计划

时间:2021-07-01 10:21:17 帮助过:10人阅读

.其定义基本与B-树同,除了: 2.非叶子结点的子树指针与关键字个数相同; 3.非叶子结点的子树指针P[i],指向关键字值属于[K[i], K[i+1])的子树(B-树是开区间); 5.为所有叶子结点增加一个链指针; 6.所有关键字都在叶子结点出现; 如:(M=3

技术分享图片 

   B+的搜索与B-树也基本相同,区别是B+树只有达到叶子结点才命中(B-树可以在非叶子结点命中),其性能也等价于在关键字全集做一次二分查找;

       B+的特性:

       1.所有关键字都出现在叶子结点的链表中(稠密索引),且链表中的关键字恰好是有序的;
       2.不可能在非叶子结点命中;
       3.非叶子结点相当于是叶子结点的索引(稀疏索引),叶子结点相当于是存储(关键字)数据的数据层;
       4.更适合文件索引系统;

1.1.7 HASH:HASH算法

  哈希索引只有Memory, NDB两种引擎支持,Memory引擎默认支持哈希索引,如果多个hash值相同,出现哈希碰撞,那么索引以链表方式存储。

  但是,Memory引擎表只对能够适合机器的内存切实有限的数据集。

  要使InnoDB或MyISAM支持哈希索引,可以通过伪哈希索引来实现,叫自适应哈希索引。

  主要通过增加一个字段,存储hash值,将hash值建立索引,在插入和更新的时候,建立触发器,自动添加计算后的hash到表里。

1.1.8 其他的索引

FULLTEXT:全文索引
RTREE:R树索引

1.2 MySQL索引管理

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

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

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

添加索引的方法:

alter table test add index index_name(name);
create index index_name on test(name);

语法格式:

alter tableadd index 索引名称(name);

1.2.1 创建普通索引

创建普通索引方法一:

mysql> ALTER TABLE PLAYERS ADD INDEX   name_idx(NAME);
mysql> desc PLAYERS;
+------------+-------------+------+-----+---------+-------+
| Field      | Type        | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| NAME       | char(15)    | NO   | MUL | NULL    |       |

创建普通索引方法二:

mysql> ALTER TABLE PLAYERS ADD INDEX   name_idx(NAME);
mysql> desc PLAYERS;
+------------+-------------+------+-----+---------+-------+
| Field      | Type        | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| NAME       | char(15)    | NO   | MUL | NULL    |       |

1.2.2 删除索引

alter table PLAYERS delete INDEX  name_idx;
mysql> show index from  PLAYERS\G
*************************** 1. row ***************************
        Table: PLAYERS
   Non_unique: 0
     Key_name: PRIMARY
 Seq_in_index: 1
  Column_name: PLAYERNO
    Collation: A
  Cardinality: 14
     Sub_part: NULL
       Packed: NULL
         Null: 
   Index_type: BTREE
      Comment: 
Index_comment:

1.3 MySQL中的约束索引

主键索引

  只能有一个主键。

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

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

普通索引

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

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

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;

唯一索引

  内容唯一,但不是主键。

create unique index index_name on test(name);

1.3.1 创建主键索引

  建立表时

CREATE TABLE `test` (
`id` int(4) NOT NULL AUTO_INCREMENT,
`name` char(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=UTF8;

  建立表后增加

CREATE TABLE `test` (
`id` int(4) NOT NULL,
`name` char(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=UTF8;

增加自增主键

alter table test change id id int(4) primary key 
not null auto_increment;

1.3.2 使用字段前缀创建索引及联合索引

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

create index index_name on test(name(8));

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

where a女生 and b身高165 and c身材好
index(a,b,c)

  特点:前缀生效特性。

a,ab,abc 可以走索引。
b ac bc c 不走索引(5.6之后 ac 可以走主键索引)。

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

示例:

创建表

 create table people (id int not null auto_increment ,name char(20),sr(20),sex int ,age int, primary key (id));

创建联合索引

mysql> alter table people  add key name_sex_idx(name,sex)
    -> ;
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

   查看索引的类型

mysql> desc people;
+-------+----------+------+-----+---------+----------------+
| Field | Type     | Null | Key | Default | Extra          |
+-------+----------+------+-----+---------+----------------+
| id    | int(11)  | NO   | PRI | NULL    | auto_increment |
| name  | char(20) | YES  | MUL | NULL    |                |
| sex   | int(11)  | YES  |     | NULL    |                |
| age   | int(11)  | YES  |     | NULL    |                |
+-------+----------+------+-----+---------+----------------+

建立唯一键索引

mysql> alter table people add unique key age_uidx(age);
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

   查看数据表

mysql> desc people;
+-------+----------+------+-----+---------+----------------+
| Field | Type     | Null | Key | Default | Extra          |
+-------+----------+------+-----+---------+----------------+
| id    | int(11)  | NO   | PRI | NULL    | auto_increment |
| name  | char(20) | YES  | MUL | NULL    |                |
| sex   | int(11)  | YES  |     | NULL    |                |
| age   | int(11)  | YES  | UNI | NULL    |                |
+-------+----------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

  联合主键是联合索引的特殊形式

PRIMARY KEY (`Host`,`User`)
alter table test add sex char(4) not null;
create index ind_name_sex on test(name,sex);

前缀加联合索引

create index index_name on test(name(8),sex(2));

1.4 SQL语句优化

1.4.1 企业SQL优化思路

  1、把一个大的不使用索引的SQL语句按照功能进行拆分

  2、长的SQL语句无法使用索引,能不能变成2条短的SQL语句让它分别使用上索引。

  3、对SQL语句功能的拆分和修改

  4、减少“烂”SQL由运维(DBA)和开发交流(确认),共同确定如何改,最终由DBA执行

  5、制定开发流程

1.4.2 不适合走索引的场景

  1、唯一值少的列上不适合建立索引或者建立索引效率低。例如:性别列

  2、小表可以不建立索引,100条记录。

  3、对于数据仓库,大量全表扫描的情况,建索引反而会慢

1.4.3 查看表的唯一值数量

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

1.4.4 建立索引流程

  1、找到慢SQL。

show processlist;

    记录慢查询日志。

  2、explain select句,条件列多。

  3、查看表的唯一值数量:

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

    条件列多。可以考虑建立联合索引。

  4、建立索引(流量低谷)

force index

  5、拆开语句(和开发)。

  6、like ‘%%‘不用mysql

  7、进行判断重复的行数

查看行数:

mysql> select count(*) from city;
+----------+
| count(*) |
+----------+
|     4079 |
+----------+
1 row in set (0.00 sec)

查看去重后的行数:

mysql> select count(distinct countrycode) from city;
+-----------------------------+
| count(distinct countrycode) |
+-----------------------------+
|                         232 |
+-----------------------------+
1 row in set (0.00 sec)

1.5 用explain查看SQL的执行计划

  在工作中,我们用于捕捉性能问题最常用的就是打开慢查询,定位执行效率差的SQL,那么当我们定位到一个SQL以后还不算完事,我们还需要知道该SQL的执行计划,比如是全表扫描,还是索引扫描,这些都需要通过EXPLAIN去完成。

  EXPLAIN命令是查看优化器如何决定执行查询的主要方法。可以帮助我们深入了解MySQL的基于开销的优化器,还可以获得很多可能被优化器考虑到的访问策略的细节,以及当运行SQL语句时哪种策略预计会被优化器采用。

  需要注意的是,生成的QEP并不确定,它可能会根据很多因素发生改变。MySQL不会将一个QEP和某个给定查询绑定,QEP将由SQL语句每次执行时的实际情况确定,即便使用存储过程也是如此。尽管在存储过程中SQL语句都是预先解析过的,但QEP仍然会在每次调用存储过程的时候才被确定。

1.5.1 查看 select 语句的执行过程

mysql> explain select id,name from test where name=clsn;
+----+-------------+-------+------+---------------+----------+---------+-------+------+-------------+
| id | select_type | table | type | possible_keys | key      | key_len | ref   | rows | Extra       |
+----+-------------+-------+------+---------------+----------+---------+-------+------+-------------+
|  1 | SIMPLE      | test  | ref  | name_idx      | name_idx | 24      | const |    1 | Using where |
+----+-------------+-------+------+---------------+----------+---------+-------+------+-------------+
1 row in set (0.00 sec)

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

使用where条件查找

mysql> explain select user,host from mysql.user where user=root and host=127.0.0.1;
+----+-------------+-------+-------+---------------+---------+---------+-------------+------+-------------+
| id | select_type | table | type  | possible_keys | key     | key_len | ref         | rows | Extra       |
+----+-------------+-------+-------+---------------+---------+---------+-------------+------+-------------+
|  1 | SIMPLE      | user  | const | PRIMARY       | PRIMARY | 228     | const,const |    1 | Using index |
+----+-------------+-------+-------+---------------+---------+---------+-------------+------+-------------+
1 row in set (0.00 sec)

1.5.2 通过执行计划可以知道什么?

mysql> explain select d1.age, t2.id from (select age,name from t1 where id in (1,2))d1, t2 where d1.age=t2.age group by d1.age, t2.id order by t2.id;
+----+-------------+------------+-------+---------------+---------+---------+--------+------+---------------------------------+
| id | select_type | table      | type  | possible_keys | key     | key_len | ref    | rows | Extra                           |
+----+-------------+------------+-------+---------------+---------+---------+--------+------+---------------------------------+
|  1 | PRIMARY     | <derived2> | ALL   | NULL          | NULL    | NULL    | NULL   |    2 | Using temporary; Using filesort |
|  1 | PRIMARY     | t2         | ref   | age           | age     | 5       | d1.age |    1 | Using where; Using index        |
|  2 | DERIVED     | t1         | range | PRIMARY       | PRIMARY | 4       | NULL   |    2 | Using where                     |
+----+-------------+------------+-------+---------------+---------+---------+--------+------+---------------------------------+
3 rows in set (0.00 sec)

1.5.3 MySQL执行计划调用方式

1.EXPLAIN SELECT ……
2.EXPLAIN EXTENDED SELECT ……
  将执行计划"反编译"成SELECT语句,运行SHOW WARNINGS 可得到被MySQL优化器优化后的查询语句
3.EXPLAIN PARTITIONS SELECT ……
  用于分区表的EXPLAIN生成QEP的信息

1.5.4 执行计划包含的信息

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

1.5.5 id

  包含一组数字,表示查询中执行select子句或操作表的顺序

【示例一】id相同,执行顺序由上至下

mysql> explain select t2.* from t1, t2, t3 where t1.id=t2.id and t1.id=t3.id and t1.name=‘‘;
+----+-------------+-------+--------+---------------+---------+---------+------------+------+--------------------------+
| id | select_type | table | type   | possible_keys | key     | key_len | ref        | rows | Extra                    |
+----+-------------+-------+--------+---------------+---------+---------+------------+------+--------------------------+
|  1 | SIMPLE      | t1    | ref    | PRIMARY,name  | name    | 63      | const      |    1 | Using where; Using index |
|  1 | SIMPLE      | t2    | eq_ref | PRIMARY       | PRIMARY | 4       | test.t1.id |    1 |                          |
|  1 | SIMPLE      | t3    | eq_ref | PRIMARY       | PRIMARY | 4       | test.t1.id |    1 | Using index              |
+----+-------------+-------+--------+---------------+---------+---------+------------+------+--------------------------+
3 rows in set (0.00 sec)

【示例二】如果是子查询,id的序号会递增,id值越大优先级越高,越先被执行

mysql> explain select t2.* from t2 where id = (select id from t1 where id = (select t3.id from t3 where t3.name=‘‘));
+----+-------------+-------+------+---------------+------+---------+------+------+-----------------------------------------------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows | Extra                                               |
+----+-------------+-------+------+---------------+------+---------+------+------+-----------------------------------------------------+
|  1 | PRIMARY     | NULL  | NULL | NULL          | NULL | NULL    | NULL | NULL | Impossible WHERE noticed after reading const tables |
|  2 | SUBQUERY    | NULL  | NULL | NULL          | NULL | NULL    | NULL | NULL | no matching row in const table                      |
|  3 | SUBQUERY    | t3    | ref  | name          | name | 63      |      |    1 | Using where; Using index                            |
+----+-------------+-------+------+---------------+------+---------+------+------+-----------------------------------------------------+
3 rows in set (0.00 sec)

【示例三】id如果相同,可以认为是一组,从上往下顺序执行;在所有组中,id值越大,优先级越高,越先执行

mysql> explain select t2.* from (select t3.id from t3 where t3.name=‘‘)s1, t2 where s1.id=t2.id;
+----+-------------+------------+--------+---------------+---------+---------+-------+------+--------------------------+
| id | select_type | table      | type   | possible_keys | key     | key_len | ref   | rows | Extra                    |
+----+-------------+------------+--------+---------------+---------+---------+-------+------+--------------------------+
|  1 | PRIMARY     | <derived2> | system | NULL          | NULL    | NULL    | NULL  |    1 |                          |
|  1 | PRIMARY     | t2         | const  | PRIMARY       | PRIMARY | 4       | const |    1 |                          |
|  2 | DERIVED     | t3         | ref    | name          | name    | 63      |       |    1 | Using where; Using index |
+----+-------------+------------+--------+---------------+---------+---------+-------+------+--------------------------+
3 rows in set (0.00 sec)

1.5.6 select_type

示查询中每个select子句的类型(简单OR复杂)
    a. SIMPLE:查询中不包含子查询或者UNION
    b. 查询中若包含任何复杂的子部分,最外层查询则被标记为:PRIMARY
    c. 在SELECT或WHERE列表中包含了子查询,该子查询被标记为:SUBQUERY
    d. 在FROM列表中包含的子查询被标记为:DERIVED(衍生)用来表示包含在from子句中的子查询的select,mysql会递归执行并将结果放到一个临时表中。服务器内部称为"派生表",因为该临时表是从子查询中派生出来的
    e. 若第二个SELECT出现在UNION之后,则被标记为UNION;若UNION包含在FROM子句的子查询中,外层SELECT将被标记为:DERIVED
    f. 从UNION表获取结果的SELECT被标记为:UNION RESULT

说明:

SUBQUERY和UNION还可以被标记为DEPENDENT和UNCACHEABLE。
DEPENDENT意味着select依赖于外层查询中发现的数据。
UNCACHEABLE意味着select中的某些 特性阻止结果被缓存于一个item_cache中。

【示例】

mysql> explain select d1.name, ( select id from t3) d2 from (select id,name from t1 where name=‘‘)d1 union (select name,id from t2);
+----+--------------+------------+--------+---------------+------+---------+------+------+--------------------------+
| id | select_type  | table      | type   | possible_keys | key  | key_len | ref  | rows | Extra                    |
+----+--------------+------------+--------+---------------+------+---------+------+------+--------------------------+
|  1 | PRIMARY      | <derived3> | system | NULL          | NULL | NULL    | NULL |    0 | const row not found      |
|  3 | DERIVED      | t1         | ref    | name          | name | 63      |      |    1 | Using where; Using index |
|  2 | SUBQUERY     | t3         | index  | NULL          | age  | 5       | NULL |    6 | Using index              |
|  4 | UNION        | t2         | index  | NULL          | name | 63      | NULL |    4 | Using index              |
| NULL | UNION RESULT | <union1,4> | ALL    | NULL          | NULL | NULL    | NULL | NULL |                          |
+----+--------------+------------+--------+---------------+------+---------+------+------+--------------------------+
5 rows in set (0.00 sec)

内容说明:

第一行:id列为1,表示第一个select,select_type列的primary表 示该查询为外层查询,table列被标记为<derived3>,表示查询结果来自一个衍生表,其中3代表该查询衍生自第三个select查询,即id为3的select。
第二行:id为3,表示该查询的执行次序为2( 4 => 3

                  

	 	
                    
                    
                    
                    
                    
                

人气教程排行