sql优化
原因:性能低、执行时间太长,SQL语句欠佳(连接查询)、索引失效,服务器参数设置不合理
sql执行过程 :select distinct ..from ..join ..on ..where ..group by ..having ..order by ..limit
sql解析过程:from.. on.. join.. where.. group by ..having ..select dinstinct ..order by limit..
优化索引
索引:相当与书的目录
索引:index是帮助MYSQL高效获取数据的数据结构。索引是数据结构(树:B+树(默认)、HasH树)
索引的弊端:
1.索引本身很大,可以存放在内存/硬盘
2.索引不是所有情况均适用:少量数据、频繁更新的字段、很少使用的字段
3.索引会降低增删改的效率
索引的优势:
1.提高查询的效率(降低IO使用率)
2.降低CPU的使用率
索引
分类:
单值索引:单列,一个表可以多个单值索引
唯一索引:不能重复
复合索引:多个列构成的索引(相当与二级目录)
创建索引:
create 索引类型 索引名 on 表(字段)
alter table 表名 索引类型 索引名(字段)
单值:
create index id_index on emp(id)
alter table emp add index emp(id)
唯一索引:
create unique index name_index on emp(name)
复合索引:
create index id_name_index on emp(id,name)
查询索引:
show index from 表名
show index from 表名 \G
删除索引:
drop index 索引名 on 表名
SQL性能问题
a.分析SQL的执行计划:explain
b.MySQL查询优化尤其会干扰我们的优化
id:编号
select_type :查询类型
table: 表
possible_keys : 预测用到的索引
key: 实际使用的索引
key_len:实际使用的的长度
ref : 表之间的引用
rows: 通过索引查询到的数据量
Extra: 额外的信息
分析
id: id值相同,从上往下顺序执行(数据量影响执行顺序)
emp1(3条) -> emp2(4条) -> emp3(5条)
emp2(4条) -> emp3(5条) -> emp1(6条)
id值不相同,id值越大越优先查询(本质:在嵌套子查询时,先查内层,再查外层)
id有相同,又有不同,id值越大优先,id值相同,按照顺序执行
select_type(查询类型)
primary:包含子查询SQL中的 主查询(最外层)
subquery: 包含子查询的 子查询(非最外层)
simple: 简单查询(不包含子查询、union)
derived: 衍生查询(使用到了临时表)
type(索引类型、类型)
system>const>eq_ref>ref>range>index>all
其中:system、const只是理想情况;实际能达到