我试图优化这个慢查询(> 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()是不使用任何索引的好方法。这将解释你的减速。 –