SQL優化——索引筆記

SQL優化

SQL編寫過程:
select dinstinct…from…join…on…where…group…by…having…order by …limit…
SQL解析過程:
from…on…join…where…group by…having…select dinstinct…order…by…limit…

SQL優化:主要在於 優化索引

索引可以理解爲書的目錄,用於幫助數據庫更高效的獲取數據的一種數據結構,默認使用B樹,一般還有Hash樹

索引的弊端:

1.索引本身很大,可以存放在硬盤內
2.索引不適合用於所有情況: a.少量數據 —— b.頻繁更新的字段 ———c.很少使用的字段
3.索引會減低增刪改的效率,增加查的效率。因爲增刪改會執行兩次,一次數據庫,一次樹。

優勢:

1.提高查詢效率(減低IO效率)
2.減低CPU使用效率

分類:

主鍵索引:不能重複,id,不能爲Null
唯一索引:不能重複,id,可以爲Null
單值索引:單列,一個表可以創建多個單值索引
複合索引:多個列構成的索引


創建索引:

方式一、
create 索引類型 索引名 on 表(字段)

單值:create index dept_index on biao(dept);
使用index默認單值索引。
唯一: create unique index dept_index on biao(dept);
index 前加 unique 是唯一索引
複合:create index dept_name_index on biao(dept,name);


方式二、

alter table 表名 索引類型 索引名(字段)

單值:alter table biao add index dept_index(dept);
給biao表add添加 一個單值索引,字段是dept。
唯一: alter table biao add unique index dept_index(dept);
index 前加 unique 是唯一索引
複合:alter table biao add index dept_name_index(dept,name);


查詢索引:

show index from 表名 ;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章