SQL 优化

1.为什么需要优化sql

  不好的sql可能存在的问题:性能低、执行时间长、等待时间长、sql语句欠佳(连接查询)、索引失效、服务器参数设置不合理(缓冲区、线程数)

  编写过程:select distinct..  from..  join..on.. where.. group by.. having.. order by..  limit..

  解析过程:from.. on.. join.. where.. group by.. having.. select distinct.. order by.. limit.. 

2.索引

  第一步可以从索引入手,sql优化主要就是在优化索引

  索引相当于书的目录,可以是B+树结构、hash结构,会占用一定的空间

  安利一个蛮好用的网站

https://www.cs.usfca.edu/~galles/visualization/Algorithms.html

  优点:索引可以提高查的效率,提高  order by column 排序的效率(因为树本身就排好序了)

  缺点:索引会降低增删改的效率,所以对于频繁更新的字段不适用(一个表查询操作比增删改要频繁的多)

  下面,以一个B树来直观展示一下索引的查询流程(注意,mysql使用的是b+树,这里只是为了展示)

  如果执行:

select * from user where age=44

  在没有索引的情况下得从上到下查询,需要6次比较,添加了索引呢,只需要4次

  不过,我们得清除索引的应用场景,对于基本有序的列,使用索引并不明智,如上面的 id,B树为

  

 

  可以很直观的看出来,查找次数并没有减少。

  索引的创建

/*create 创建索引 (单值索引、唯一索引、复合索引)*/
create index index_name on table_name(column1);
create unique index index_name on table_name(column1);
create index index_name on table_name(column1,column2);
/*alter 添加索引 (单值索引、唯一索引、复合索引)*/
alter table table_name add index index_name(column1);
alter table table_name add unique index index_name(column1);
alter table table_name add index index_name(column1,column2);

   索引的查询和删除

/*查询*/  show index from table_name;
/*查询索引可以当成查询一个表来操作 比如可以加上where 例如:show index from tb_user where key_name='UserIndex'*/
/*删除*/ drop index index_name on table_name;

 3.  mysql优化

  

  

  

posted @ 2019-06-30 22:59  wskxy  阅读(542)  评论(0编辑  收藏  举报