Mysql 索引優化

MYSQL 索引優化

primary key 主鍵索引

index 普通索引

full text 全文索引,一般比較少用到

spatial 空間索引,和GIS地理有關,很少用到

 

t1表

id name class
1 aa 555
2 bb2 222
3 aa1 111
4 bb1 555
5 cc1 333
6 dd 888
7 dd 666

 


select * from t1 group by class;

默認排序列表出結果,如加上 select * from t1 group by class ordey by null;

則減少排序減少資源佔用

group by 後面的字段也不需要索引,用了索引還是要全表查詢!

select * from t1 group by class having class>100;

having 後的條件一定要在搜索中的結果中有,換句說group by中含有 class做爲組合所以having不會報錯,如select * from t1 group by class having id>1; *中含有id,不會報錯

但 select name,class from t1 group by class having id>1; 由於group by class 和name,class都不包含id就會報錯! 

總之,having後的條件一定要體現在SQL語句的搜索中,不然會報錯!

相反,order by ,where 則沒有這樣的限制!

還有一點特別重要,group by 和where不能同時出現在SQL語句中,不能共存

select id,name,class from one group by class having id>1;

可行,但

select id,name,class from one group by class where id>1;

就會報錯!

select * from one where id>1;和 select * from one having id>1;獲得結果是一樣的,但哪個更高效呢?當然是where了,having是搜索出結果把數據取出來後把不符合條件的數據行剔除,而where是在數據的搜索過程中把不符合條件的數據行剔除,根本沒有取出不符合條件的數據行,所以顯得更高效!


desc select * from t1 where class='555';

若沒有在class做index 索引則全表搜索,做了索引index,則是索引搜索!!!

若在name和class 上做了複合索引,依據左向原則,還是要全表搜索

若是desc select * from t1 where name='dd'; 則用上了索引,所以做複合索引時最好把where後的第一個條件經常使用的做左項索引,就是排在前面!!!

若是select * from t1 where name='dd' and class='888' 則最好name,class做成複合索引

order by 後面不需要做索引.如

 desc select * from one order by name desc limit 1,3;

order by 不會去索引文件中搜索查詢,用了索引也沒有用

 

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