0

我正在尝试优化以下查询(需要 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) 上创建复合索引并删除视图索引,但没有帮助。products表有 600k 行,并且products_shops有 740k 行。

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

4

1 回答 1

0

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

sale_price
price

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

于 2013-11-07T12:59:53.957 回答