开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 4 天 MySQL 复习笔记(一)------ 索引 [1/3] - 掘金 (juejin.cn)
1. 索引的基本语法
1.1 创建索引
create [ UNIQUE | FULLTEXT ] index index_name ON table_name(index_col_name(length),...);
例如:
create unique index index_phone on student(phone) 单列索引
或者
create index index_name_sex on student(name,sex) 联合索引
通过修改表结构创建索引:
alter table table_name add [ UNIQUE | FULLTEXT ] index index_name ON(column(length))
例如:
alter table student add unique index index_id on (id)
注意:其中(length)是指对该字段前几个长度的内容做索引,常用在数据比较长的内容上,例如一篇网页的标题,论坛的内容等。
1.2 删除索引
drop index index_name on table_name
例如
drop index index_phone on student
1.3 查看索引
show index from table_name
例如: show index from student
2. 索引的性能分析
2.1 慢查询日志
慢查询日志记录了所有执行时间超过指定参数(long_query_time,单位:秒,默认10秒)的所有SQL语句的日志。
Mysql的慢查询日志默认没有开启,需要在MySQL配置文件(/etc/my.cnf)中配置以下信息
开启MySQL慢查询日志开关
slow_query_log=1
设置慢查询日志时间为2秒,SQl语句执行时间超过2秒就会视为慢查询,自动记录慢查询日志
long_query_time=2
2.2 profiles
show profiles 能够在做SQL优化时帮助我们了解时间都耗费到哪里去了。
不同版本的Mysql可能对profile的支持不同。通过have_profiling 参数能够看到当前MySQL是否支持profile操作
使用set global/session profiling = 1可以设置开启profiles
使用 show profiles 查看当前每一条sql语句执行耗时
查看指定query_id的sql执行耗时 show profile for query query_id
查看指定query_id的sql语句CPU使用情况 show profile cpu for query query_id
2.3 explain执行计划
在sql语句之前使用explain关键字可以查看当前sql语句的执行时间以及用到的索引情况
例如:
explain select * from student where user = 1
id :select查询的序列号,id相同则执行顺序从上到下,id不同从大到小
select_type :查询的类型
table:查询的表
partitions:分区情况
type:连接类型,性能由好到差分别是NULL、system 、const 、 eq_ref 、ref 、range 、index 、 all
- NULL 只有在不查询表的时候才会出现
- system 只有在访问系统表的时候才会出现
- const 一般根据主键或者唯一索引查询的时候会出现
- ref 一般使用非唯一索引的时候会出现
- all 全表扫描的时候会出现
possible_keys:可能用到的索引
key :实际用到的索引
key_len: 使用到索引的字节数,该值为索引可能的最大长度,并非实际使用长度,在不损失精度的前提下,长度越短越好
rows:MySQL认为必须要执行查询的行数,在innodb引擎的表中是一个估计值,可能并不总是精确的
filtered:表示返回结果的行数占需读取行数的百分比,filtered值越大越好