基於索引的MySQL最佳化

來源:互聯網
上載者:User

標籤:tac   explain   層級   span   wiki   chm   ant   mys   子查詢   

今天查看MySQL慢查詢日誌,查看一個四表關聯的SQL操作,耗時1006s。這次也是基於基於子查詢的思路,對上表進行最佳化。使時間複雜度降到n^2層級。但最佳化之後時間反而是原來的三倍多。

原SQL語句:

explain select distinct b.businessId from
 gte_order o,
gte_jy_contract c,
flow_ru_participant tp,
flow_ru_business b
where b.businessId = o.businessId
 and o.businessId=c.businessId
 and b.businessId = tp.businessId
 and o.cityCode = 120000
 and tp.status = 0
 and o.status in
 (
-1,6,7
 )
order by o.createTime;

耗時1s多,

最佳化後的語句:

#3 s 334 ms
desc select distinct tempB.businessId #distinct導致temportory
from (select o.businessId,o.createTime
 from gte_order o,gte_jy_contract c
where o.businessId = c.businessId and o.status in (-1,6,7) and o.cityCode = 120000) as tempA,(select b.businessId
 from flow_ru_participant p,flow_ru_business b
where b.businessId = p.businessId and p.status = 0) as tempB
where tempA.businessId = tempB.businessId
order by tempA.createTime;#filesort
耗時3s多。

 

查看其執行計畫後可知:

 

修改後的執行計畫:

 

由於索引的存在:原SQL只會遍曆自己的索引(涉及的行為72426),然後一次去查詢另外三表的索引(涉及的行為1,1,3),所以其時間複雜度為O(n)層級。

然而子查詢的方式,首先兩表直接查詢時間複雜度為O(n),兩個表衍生出來的暫存資料表之間再進行查詢,時間複雜度為O(n),索引的存在讓時間複雜度降到O(n)。此時總時間複雜度大致為3*O(n),符合時間查詢時間的結果。

總結:

 

對於SQL查詢來說,索引是其效率最佳化的最主要方式,但由於索引其本身的缺點及其局限性,資料表的索引是有限的,功能也是有限的。所以需要輔助於其它方式。但是書寫SQL語句時,應首先考慮索引的情況。

如:如何建索引,如何用索引,沒有索引時如何最佳化。

 

另:關於SQL逾時問題,與SQL無關,猜測是網路的原因。

基於索引的MySQL最佳化

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.