我正在尝试优化以下查询(需要 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
列已编入索引,但我无法理解为什么它很慢。