【发布时间】:2013-05-03 21:18:49
【问题描述】:
在 InnoDB 中使用 MySQL 5.5。 有一个类似的查询
SELECT
count(distinct a.thing_id) as new_thing_count,
sum(b.price) as new_thing_spend
FROM thing ii
LEFT OUTER JOIN thing a
ON a.customer_id = ii.customer_id
AND a.created_at >= '2013-01-01'
AND a.created_at <= '2013-03-31'
JOIN whatsit b
ON b.whatsit_id = a.original_whatsit_id
WHERE ii.customer_id = 3
在哪里
-
thing的基数约为 25k,其中 3.5k 属于客户 3 - 有 12 个可能的
customer_ids
现在,当我使用customer_id 上的索引运行此查询时,大约需要 10 秒。当我删除索引时,需要 0.03 秒。
我不知道为什么会这样。这是没有索引的解释结果:
1 SIMPLE ii ALL 24937 Using where
1 SIMPLE a ALL 24937 Using where; Using join buffer
1 SIMPLE b eq_ref PRIMARY PRIMARY 4 db.a.original_whatsit_id 1
这里是索引 (thing_customer)
1 SIMPLE ii ref thing_customer thing_customer 4 const 3409 Using index
1 SIMPLE a ref thing_customer thing_customer 4 const 3409 Using where
1 SIMPLE b eq_ref PRIMARY PRIMARY 4 db.a.original_whatsit_id 1
有人能帮我解释一下为什么这个索引在逻辑上看起来不应该的情况下让事情变慢这么多吗?
【问题讨论】: