1

I have the following query:

select * 
 from products as p
 left join files as f on f.contentid = p.productid
   where 
     p.state = 'active' AND 
     p.price > 0 order by p.created DESC 
   LIMIT 2200

Currently, this query takes about 1.7 seconds for 2200 rows. What I don't understand is, why does this time not decrease when I change the limit from 2200 to 10, and more importantly, what I can do to speed it up?

8
  • 1
    Are your ID fields indexed (contentid, productid)? Commented Mar 12, 2012 at 12:52
  • Do you need all fields of table products? Commented Mar 12, 2012 at 12:53
  • 3
    Time to order the data is the same for 10, 200, 2200 and all the rows. First data will be ordered then limit will be applied. Commented Mar 12, 2012 at 12:54
  • SELECT p.field1, p.field2, p.fieldn FROM products p, files f WHERE f.contentid = p.productid AND p.state = 'active' AND p.price > 0 ORDER BY p.created DESC LIMIT 2200 Commented Mar 12, 2012 at 12:55
  • 1
    If you don't need every field from the two tables, you may also want to consider selecting the specific fields (instead of *) to reduce the size of the returned rows. That's helped me in situations in the past (especilly text fields). Commented Mar 12, 2012 at 12:55

3 Answers 3

5

By adding INDEX on files [contentid] and products [productid], it can speed up your query.

Sign up to request clarification or add additional context in comments.

Comments

1

Try :

EXPLAIN select * 
 from products p
 left join files f on f.contentid = p.productid
   where 
     p.state = 'active' AND 
     p.price > 0 order by p.created DESC 
   LIMIT 2200

to see what indexes you need

4 Comments

+ Options id select_type table type possible_keys key key_len ref rows Extra 1 SIMPLE p ALL NULL NULL NULL NULL 1577 Using where; Using temporary; Using filesort 1 SIMPLE f ALL NULL NULL NULL NULL 1595
As I see possible_keys column is null, so you got no possible keys for the query to use. Try to add indexes for files contentid and for products productid
I did that, it fixed the problem, but I'm unsure as to how to use explain. It ended up not giving me the answer... or at least, I don't know how to make sense of it...
@RD Here is a tutorial about explain eecho.info/Echo/database/using-explain
1

Usually I just play with the query to see what minimizes runtime the best. If necessary, work out the problem using Relational Algebra and look for places to optimize from there. Here's my suggestion:

 SELECT * 
 FROM products as p, files f
    WHERE f.contentid = p.productid 
    AND p.state = 'active'
    AND p.price > 0 
    ORDER BY p.created DESC
    LIMIT 2200

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.