我有一个产品和产品表的产品销售以及在这些产品上完成的所有销售操作。这些表通过Sales.PRODUCT_ID列连接。
我想今天购买10种最常销售的产品,我所做的就是:
SELECT product.* , COUNT( sale.ID ) SUMSELL
FROM Products product
LEFT JOIN
Sales sale
ON
sale.ANKIETA_ID = product.ID AND
sale.DATE >= DATE_SUB( NOW( ) , INTERVAL 1 DAY )
GROUP BY product.ID
ORDER BY SUMSELL DESC
LIMIT 0 , 10
但它的表现非常缓慢。如何提高此特定查询的效果?
答案 0 :(得分:1)
摆脱LEFT JOIN
:
SELECT product.*, sumsell
FROM (
SELECT ankieta_id, COUNT(*) AS sumsell
FROM sale
WHERE sale.DATE >= DATE_SUB( NOW( ) , INTERVAL 1 DAY )
GROUP BY
ankieta_id
) s
JOIN product
ON product.id = s.ankieta_id
ORDER BY
SUMSELL DESC
LIMIT 10
在sale (date, ankieta_id)
上建立一个索引,以便快速运作。
如果您的桌子可能销售的产品少于10
,但您需要展示10
,请执行以下操作:
SELECT *
FROM (
SELECT product.*, sumsell
FROM (
SELECT ankieta_id, COUNT(*) AS sumsell
FROM sale
WHERE sale.DATE >= DATE_SUB( NOW( ) , INTERVAL 1 DAY )
GROUP BY
ankieta_id
) s
JOIN product
ON product.id = s.ankieta_id
ORDER BY
SUMSELL DESC
LIMIT 10
) p
UNION ALL
SELECT *
FROM (
SELECT product_id, 0
FROM products p
WHERE products NOT IN
(
SELECT *
FROM sale
WHERE ankieta_id = p.id
AND sale.DATE >= DATE_SUB( NOW( ) , INTERVAL 1 DAY )
) p2
LIMIT 10
) p2
ORDER BY
sumsell DESC
LIMIT 10
答案 1 :(得分:0)
您在左连接中使用sale.DATE >= DATE_SUB( NOW( ) , INTERVAL 1 DAY )
条件。我猜这就是为什么它很慢。
我建议:
WHERE
子句JOIN
代替JOIN
Sales.DATE
上添加和索引也有助于缩小查询范围SELECT product.* , COUNT( sale.ID ) SUMSELL
FROM Products product
JOIN Sales sale
ON sale.ANKIETA_ID = product.ID
WHERE sale.DATE >= DATE_SUB( NOW( ) , INTERVAL 1 DAY )
GROUP BY product.ID
ORDER BY SUMSELL DESC
LIMIT 0 , 10