SQL优化3-索引

原因:性能低、执行时间太长、等待时间太长、SQL语句欠佳(连接查询)、索引失效、服务器参数设置不合理(缓冲、线程数)

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

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


    b.SQL优化, 主要就是 在优化索引

索引: 相当于书的目录
        索引: index是帮助MYSQL高效获取数据的数据结构。索引是数据结构(树:B树(默认)、Hash树...)
  
        索引的弊端:
            1.索引本身很大, 可以存放在内存/硬盘(通常为 硬盘)
            2.索引不是所有情况均适用: a.少量数据  b.频繁更新的字段   c.很少使用的字段
            3.索引会降低增删改的效率(增删改  查)

        优势:1提高查询效率(降低IO使用率)
              2.降低CPU使用率 (...order by age desc,因为 B树索引 本身就是一个 好排序的结构,因此在排序时  可以直接使用)
            

索引
    分类:
        主键索引:  不能重复。id    不能是null
        唯一索引  :不能重复。id    可以是null
        单值索引  : 单列, age ;一个表可以多个单值索引,name。
        复合索引  :多个列构成的索引 (相当于 二级目录 :  z: zhao)  (name,age)   (a,b,c,d,...,n)
    创建索引:
        方式一:
        create 索引类型  索引名  on 表(字段)
        单值:
        create index   dept_index on  tb(dept);
        唯一:
        create unique index  name_index on tb(name) ;
        复合索引
        create index dept_name_index on tb(dept,name);

        方式二:alter table 表名 索引类型  索引名(字段)
        
        单值:
        alter table tb add index dept_index(dept) ;
        唯一:
        alter table tb add unique index name_index(name);
        复合索引
        alter table tb add index dept_name_index(dept,name);

        注意:如果一个字段是primary key,则改字段默认就是 主键索引    
    

        删除索引:
        drop index 索引名 on 表名 ;
        drop index name_index on tb ;

        查询索引:
        show index from 表名 ;
        show index from 表名 \G

猜你喜欢

转载自blog.csdn.net/qq_41332728/article/details/84771964