考虑以下两个查询:添加WHERE子句使查询很慢
select a.*, c.*
from account a
join customer c on a.customer_id = c.id
join import i on a.import_id = i.id
join import_bundle ib on i.import_bundle_id = ib.id
和
select a.*, c.*
from account a
join customer c on a.customer_id = c.id
join import i on a.import_id = i.id
join import_bundle ib on i.import_bundle_id = ib.id
where ib.id = 8
第一个查询速度快,第二个是超级慢。任何想法为什么?我猜我需要一个索引或其他东西,但我不明白索引的工作原理。我正在使用MySQL。
这里的,如果我在第二查询做一个EXPLAIN
会发生什么:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE ib const PRIMARY PRIMARY 8 const 1 Using index
1 SIMPLE c ALL PRIMARY 144858
1 SIMPLE a ref fk_account_customer_id,fk_account_import_id fk_account_customer_id 8 mcif.c.id 2
1 SIMPLE i eq_ref PRIMARY,import_bundle_id PRIMARY 8 mcif.a.import_id 1 Using where
我不知道如何解释,虽然。
编辑:这是我最后使用:
select a.*,
c.*
from account a
join customer c on a.customer_id = c.id
join (select id,
import_bundle_id
from import
where import_bundle_id = 8) i on a.import_id = i.id
join import_bundle ib on i.import_bundle_id = ib.id
上import_bundle.id
添加索引什么也没做。
查询计划看起来像什么?索引涵盖ib.id? – 2010-11-19 19:46:08
你是什么意思,“查询计划看起来像什么?” – 2010-11-19 20:14:10
有时,事情并不像他们看起来那样。你如何比较这两个查询?你看过检索_first_记录的时间还是_last_记录。后者是应该测量的东西,但如果您是从SQL客户端应用程序开始工作,则只需查看前者即可。 – Axn 2010-11-19 20:20:39