views:

33

answers:

2

I have two tables, jos_eimcart_customers_addresses and jos_eimcart_customers. I want to pull all records from the customers table, and include address information where available from the addresses table. The query does work, but on my localhost machine it took over a minute to run. On localhost, the tables are about 8000 rows each, but in production the tables could have upwards of 25,000 rows each. Is there any way to optimize this so it doesn't take as long? Both tables have an index on the id field, which is primary key. Is there some other index I need to create that would help this run faster? Should the addresses table have an index on the customer_id field, since it's a foreign key? I have other database queries that are similar and run on much larger tables, more quickly.

(EDITED TO ADD: There can be more than one address record per customer, so customer_id is not a unique value in the addresses table.)

select 
    c.firstname,
    c.lastname,
    c.email as customer_email, 
    a.email as address_email,
    c.phone as customer_phone,
    a.phone as address_phone,
    a.company,
    a.address1,
    a.address2,
    a.city,
    a.state,a.zip, 
    c.last_signin
from jos_eimcart_customers c
    left join  jos_eimcart_customers_addresses a  
    on c.id = a.customer_id  
order by c.last_signin desc

EDITED TO ADD: Explain results

id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra
==========================================================================================
1  | SIMPLE      |  c    |  ALL |   NULL        | NULL| NULL    |NULL |6175  |Using temporary; Using filesort
---------------------------------------------------------------------------------------
1  | SIMPLE      |  a    |  ALL |   NULL        | NULL| NULL    |NULL |8111  |
+2  A: 

Short answer: Yes, customer_id should have index.

Better answer: It would be best to find a query analyzer for MySql and use it to determine what the actual cause of the slow down is.

For example you could put EXPLAIN before your select and see what the results is.

Optimizing MySQL: Queries and Indexes

darren
Edited to add EXPLAIN results.
EmmyS
+2  A: 

You should create an index on a.customer_id. It doesn't need to be a unique index, but it should definitely be indexed.

Try creating an index and see if it is faster. For further optimisation, you can use SQL's EXPLAIN to see if your query is using indexes where it should be.

Try http://www.dbtuna.com/article.asp?id=14 and http://www.devshed.com/c/a/MySQL/MySQL-Optimization-part-1/2/ for a bit of info on EXPLAIN.

BudgieInWA
WOW! I added an index on a.customer_id, and the query went from 84 seconds to 0.0168 seconds. Big difference!
EmmyS
FYI, I'm accepting this answer over darren's only because it came in 2 minutes earlier - both have basically the same answer, so there's no other way to decide who wins!
EmmyS