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

來源:互聯網
上載者:User

標籤:

/*SELECT count(*) FROM (*/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) timeFROM t_goutongGROUP 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 將不能使用索引!

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.