擺脫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
你有ID和日期索引嗎? – 2010-03-05 17:08:47