什麼是索引:
索引的作用相當於圖書的目錄,可以根據目錄中的頁碼快速找到所需的內容。
建立索引合適的列
經常用作where條件的列,order by排序的列
資料列不重複而且並不是唯一的幾個值
不被經常修改的列
普通查詢
select * from emp where empno=100002
查詢快取
show global variables like '%query_cache%'
表的引擎 innodb:第一次查詢走資料檔案,再次回走快取
show variables like '%storage_engine%'
加入索引
alter table emp add index(empno)select * from emp where empno=100002
innodb:frm為表結構檔案 ibd為索引+資料 檔案
是否使用了索引
explain select * from emp where empno=100002
新增組合索引 (第一個索引列會使用索引,第二個索引列單獨使用的時候不會使用索引)
alter table dept add index my_ind (dname,loc)select * from dept where dname='afzirjvzno'
explain select * from dept where dname='afzirjvzno'
explain select * from dept where dname='afzirjvzno' and loc='iwhzzywk'
explain select * from dept where loc='iwhzzywk' and dname='afzirjvzno'
模糊查詢 如果like前加 % 不會使用索引
explain select * from dapt where dname like '%afzirjvzno%'
使用or,or不會使用索引,
explain select * from dept where loc='iwhzzywk' or dname='afzirjvzno'
需保證列都有索引
explain select * from dept where deptno='10070' or dname='afzirjvzno'
判斷是否為null 應使用in
explain select * from dept where dname=null
explain select * from dept where dname in null
group by 預設不是用索引
explain select * from emp group by deptnoexplain select * from emp group by deptno order by null
查詢時儘量少用 >= <=等等
explain select * from dept where deptno<'10070'
注意事項
不要在列上進行運算
不使用not in操作
not in操作都不會使用索引將進行全表掃描。not in可以not exists代替
MySQL索引優化
一 什麼是索引?索引用來快速地尋找那些具有特定值的記錄,所有mysql索引都以b 樹的形式儲存。如果沒有索引,執行查詢時mysql必須從第一個記錄開始掃描整個表的所有記錄,直至找到符合要求的記錄。表裡面的記錄數量越多,這個操作的代價就越高。如果作為搜尋條件的列上已經建立了索引,mysql無需掃描任何...
mysql索引優化
1.mysql將所有資料都邏輯地存放在ib data1檔案中,我們稱之為表空間。當然,你也可以一個表對應一個物理檔案,將innodb file per table設定成on即可。2.表空間又劃為成段,有資料段 leaf node segment 索引段 none leaf node segment ...
MySQL索引優化
一 什麼是索引?索引用來快速地尋找那些具有特定值的記錄,所有mysql索引都以b 樹的形式儲存。如果沒有索引,執行查詢時mysql必須從第一個記錄開始掃描整個表的所有記錄,直至找到符合要求的記錄。表裡面的記錄數量越多,這個操作的代價就越高。如果作為搜尋條件的列上已經建立了索引,mysql無需掃描任何...