优化MySQL加入查询?

时间:2012-03-12 12:51:10

标签: mysql sql

我有以下查询:

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

目前,对于2200行,此查询大约需要1.7秒。我不明白的是,为什么这个时间不会减少,当我将限制从2200改为10,更重要的是,我能做些什么来加快它?

3 个答案:

答案 0 :(得分:5)

files [contentid]products [productid]上添加INDEX,可以加快查询速度。

答案 1 :(得分:1)

尝试:

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

查看您需要的索引

答案 2 :(得分:1)

通常我只是使用查询来查看最佳运行时间的最小化。如有必要,使用Relational Algebra解决问题,并从那里寻找要优化的地方。这是我的建议:

 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
相关问题