tags:

views:

32

answers:

2

This query executes in a fraction of a second:

SELECT customers.customers_id, customers_firstname, customers_lastname, customers.customers_email_address, max(date_purchased) 
FROM customers join orders on customers.customers_id = orders.customers_id 
group by customers.customers_id;

If I change the join to a left join, it seems to hang. I tried limiting it to 10 records, and it still takes 9 seconds. What am I doing wrong?

Thanks in advance.

+2  A: 

Do you have an index created on the join criterias?

Is customers_Id indexed on the orders table?

you can see if there are any indicies on the table with the following

SHOW INDEXES FROM Orders;

To create an index

CREATE INDEX ix_order_customersId ON Orders (customers_id);
clyc
This is usually the first thing you'll need to check, if there's no index then chances are its scanning through all records (which is slow). If you want more info on what is happening try running EXPLAIN on your query, see here: http://dev.mysql.com/doc/refman/5.1/en/explain.html
Dave
That was it. Thank you.
Jay
Just thinking about this, shouldn't there be a relationship between customer and order? i.e customers_id should be a foreign key constraint
clyc
A: 

for investigating the problem, you could try EXPLAIN SELECT ....., that will list you what are the indexes/cardinality of the request and why it is taking that much time.

dweeves