Consider the following two queries:
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
and
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
The first query is fast and the second one is super slow. Any idea why? I’m guessing I need an index or something but I don’t understand how indexes work. I’m using MySQL.
Here’s what happens if I do an EXPLAIN on the second query:
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
I don’t know how to interpret that, though.
Edit: this is what I ended up using:
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
Adding an index on import_bundle.id didn’t do anything.
Regarding performance, in your query, you really need a.* and c.*?
So, the use of an index does not improve enough. I’m not familiar with mysql but could you try a join with a subquery like this?
select a.*, c.* from account a join customer c on a.customer_id = c.id join ( SELECT id, import_bundle_id FROM import WHERE id = 8 ) as i on a.import_id = i.id join import_bundle ib on i.import_bundle_id = ib.id where ib.id = 8