標籤: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最佳化