索引

## 一、索引种类

1、普通索引:加速查询

create index 索引的名字 on 表名(列名)

2、唯一索引:加速查询与约束 unique index

create unique index 索引的名字 on 表名(列名)

3、主键索引:在创建表的时候primary key 就是主键索引

# 添加主键
alter table 表名 add primary key(列名);

# 删除主键
alter table 表名 drop primary key;

alter table 表名 modify 列名 int,drop primary key;

4、组合索引(联合索引)

create index 索引名 on 表名(列名1,列名2);

5、索引名词:
覆盖索引:在索引文件中直接获取数据
索引合并:把多个单列索引合并成使用

select * from userinfo where  name = 'sb' and id='123';

二、正确使用索引

#不能使用like与函数

#查询的时候类型一定要一致

#!= 这个如果是主键才走索引

#>  如果是主键或索引是整数类型就走索引

#order by 排序的时候选择的映射如果是索引就走索引,不是索引则不走

#组合索引最左前缀
	如果组合索引为(name,email)
	name and email	-- 使用索引
	name    -- 使用索引
	email   -- 不使用索引

索引注意

1、避免使用select *

2、尽量使用count(1)

3、创建表的时候尽量使用char代替varchar

4、表的字段顺序固定长度的字段优先

5、组合索引代替多个单列索引(经常使用多个条件查询的时候)

6、尽量使用短索引 (create index ix_title on tb(title(16));特殊的数据类型 text类型)

7、使用join代替子查询

8、索引散列(重复少)不适合用于建索引,例如:性别不合适

三、执行计划

explain + 查询SQL 用于显示SQL的执行参数,根据参考信息可以进行SQL优化

explain select * from userinfo;
 查询时的访问方式,性能对比:
 			all < index < range < index_merge < ref_or_null < ref < eq_ref < system/const 
 			
 all  : 从头到尾进行查询    select * from userinfo;
 
 index: 全索引搜索,对索引从头到尾进行找一遍    select id from userinfo;
 
 range: 范围查询   select id,name from userinfo where name='sb';
 
 index_maerge:  合并搜索,多个单列索引进行查找   
 select *  from userinfo where name = 'alex' or nid in (11,22,33);
 
 ref_or_null:  该类型如同ref 但是添加了联合查询可以查询包含null值的行
 
 ref : 根据索引查找一个或多个值   select id,name from userinfo where id;
 
 eq_ref: 查询时使用primary key 或 unique 类型的索引
 
 const:常量,表里最多有一个匹配行,仅有一行,只读取一次   select id from userinfo where id = 2 ;
 
 system:系统   表仅有一行(=系统表)。这是const联接类型的一个特例   
 select * from (select id from userinfo where id = 1) as A;

四、慢日志记录:

开启慢查询日志记录,可以让Mysql记录下查询超过指定时间的语句,可以定位分析性能的瓶颈,才能更好的优化数据库系统的性能

查询慢日志是否开启
show variables like 'slow_query%';

开启慢日志
set grobal slow_query_log=1;
或:
	在my.cnf 文件中
         找到[myini]下面添加:
           slow_query_log =1   #开启为1
        slow_query_log_file=C:\mysql-5.6.40-winx64\data\localhost-slow.log   #这里是日志存放路径
         long_query_time = 1   #指定时间,单位为秒
查看慢查询超时时间:show variables like 'long%';
posted @ 2019-10-22 11:37  tiwe  阅读(210)  评论(0编辑  收藏  举报