MySQL在连接表上的顺序很慢

时间:2013-11-07 12:51:32

标签: mysql join

我正在尝试优化以下查询(需要40秒):

SELECT SQL_CACHE p.product_ID, p.title, p.slug, p.logo, ps.price, ps.sale_price
FROM products p
JOIN products_shops ps ON p.product_ID = ps.product_ID
WHERE p.status =  'active'
AND (
p.site =  '2'
OR p.site =  '3'
)
AND ps.sale_price <>  ''
AND ps.sale_price <>  '0'
AND ps.price <>  ''
AND ps.price <>  '0'
AND ps.sale_price <>  ''
AND ps.sale_price <>  '0'
GROUP BY p.product_ID
ORDER BY p.views DESC 
LIMIT 1060 , 20

MySQL解释:http://i.stack.imgur.com/e70YF.png

我尝试过子查询但需要更长的时间:

SELECT SQL_CACHE p.product_ID, p.title, p.slug, p.logo, ps.price, ps.sale_price
FROM products_shops ps
LEFT JOIN (
   SELECT product_ID, title, slug, views, logo FROM products 
  WHERE status =  'active'
  AND (site =  '2' OR site =  '3')
  ORDER BY views DESC
) p ON p.product_ID = ps.product_ID
WHERE (ps.sale_price <>  ''
AND ps.sale_price <>  '0'
AND ps.price <>  ''
AND ps.price <>  '0'
AND ps.sale_price <>  ''
AND ps.sale_price <>  '0')
LIMIT 1060 , 20

我的索引是: products索引:http://i.stack.imgur.com/nQkLJ.png

products_shops索引:i.stack.imgur.com/UnnmQ.png

我还尝试在(product_ID,views)和drop views index上创建复合索引,但没有帮助。 products表有600k行,products_shops有740k行。

当我从查询中删除ORDER BY时,它真的很快。尽管views列已被编入索引,但我无法理解为什么它会变慢。

1 个答案:

答案 0 :(得分:0)

WHERE子句中的许多条件看起来都在没有索引的列上。可能值得为这些列添加索引。以下两者都没有索引:

sale_price
price

每个索引都应加快查询速度。