我試圖優化這個慢查詢(> 2秒)優化SQL查詢
SELECT COUNT(*)
FROM crmentity c, mdcalls_trans_activity_update mtu, mdcalls_trans mt
WHERE (mtu.dept = 'GUN' OR mtu.dept = 'gun') AND
mtu.trans_code = mt.trans_code AND
mt.activityid = c.crmid AND
MONTH(mtu.ts) = 2 AND
YEAR(mtu.ts) = YEAR(NOW()) AND
c.deleted = 0 AND
c.smownerid = 28
這是輸出,當我使用EXPLAIN:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE c index_merge PRIMARY,crmentity_smownerid_idx,crmentity_deleted_smownerid_idx,crmentity_smownerid_deleted_idx crmentity_smownerid_idx,crmentity_deleted_smownerid_idx 4,8 NULL 91 Using intersect(crmentity_smownerid_idx,crmentity_deleted_smownerid_idx); Using where; Using index
1 SIMPLE mt ref activityid activityid 4 pharex.c.crmid 60
1 SIMPLE mtu ref dept_idx dept_idx 5 const 1530 Using where
它使用我創建的索引(dept_idx ),但仍需要2秒鐘才能對1,380,384條記錄的數據集運行查詢。是否有另一種以最佳方式表達此查詢的方式?
更新:使用David的建議,查詢現在下降到幾毫秒而不是運行超過2秒(實際上,在MySQL 5.0版本上爲51秒)。
我會寫'WHERE lower(mtu.dept)='gun'AND ...'但我認爲你的數據庫已經以這種方式優化了它。 – initall
我發現,至少在Oracle中,在查詢的lhs中使用較低的值會導致大規模的減速。與其他字符串比較相比是否會導致更慢的速度... –
在列上使用lower()是不使用任何索引的好方法。這將解釋你的減速。 –