mysql 通過使用聯全索引優化Group by查詢


EXPLAIN  SELECT st.id,st.Stu_name,tmpgt.time,tmpgt.goutong FROM jingjie_students st RIGHT JOIN (
SELECT * FROM _goutong gttime,(

SELECT name_id nameid, max(time) time FROM t_goutong GROUP BY name_id) gt

WHERE gttime.name_id=gt.nameid AND gttime.time=gt.time AND gttime.time>'2015-07-19 16:18:02') tmpgt ON st.id=tmpgt.name_id; /*) student_latested;*/

//未使用聯合索引時'GROUP BY name_id'查詢使用的是全表掃描,

//使用聯合索引index name_id(name_id,time)后使用了索引:注意聯合索引建立的先后順序
復制代碼

 

熟悉Group by使用索引的情況:

 

一、GROUP BY 的索引應用
1、查詢字段必須和后面GROUP BY 一致
select TeamID from competeinfo where TeamID >10 group by TeamID。
這里就是通過TeamID 來查找。完成group by 。
2、聯合索引的應用,切記注意GROUP BY 順序,Where 條件和GROUP BY 字段得是一個索引里面的
這個表CompeteID,TeamID建立聯合索引
1)select TeamID from competeinfo where TeamID >10 and CompeteID > 100020 group by CompeteID
這個查詢用到了CompeteID,TeamID聯合索引
2)select TeamID from competeinfo where TeamID >10 and CompeteID > 100020 group by TeamID
這樣的話查詢group by中就沒有用到索引了
二、下面是總結的是聯合索引的使用
Index(Name,Age)表示在Name,Age兩列上建立聯合索引
如果where name='pp' 能使用索引
where age=25時不能使用索引
where name='pp' and age>25 能使用索引
where name ='pp' order by age 能使用索引
where name>'pp' order by age 不能使用索引
where name>'pp' order by name,age 能使用索引
order by name asc age desc 將不能使用索引!

 

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM