我有两张桌子:
1) product data
2) sales stats of these products
在表2中,我有每天每种产品的销售统计数据。我想从过去30天获得最畅销的产品。我通过以下查询意识到了这一点:
SELECT sku
FROM prod_history
WHERE insert_date >= SUBDATE(CURDATE(), INTERVAL 31 DAY)
GROUP BY sku
ORDER BY SUM(number_of_orders) DESC
LIMIT 0, 10
此查询大约需要4.5秒。
现在我想将此查询结果与产品数据表(1)连接。
我使用以下查询,但我得到的结果不正确。 我收到的结果往往不是销量最高的产品。
SELECT `prod_combined`.`sku`, `prod_combined`.`titel`, `prod_combined`.`preis_vk`, `prod_combined`.`link`
FROM `prod_combined`
WHERE (prod_combined.sku IN
(SELECT prod_combined.sku
FROM (SELECT sku FROM prod_history WHERE insert_date >= SUBDATE(CURDATE(), INTERVAL 31 DAY)
GROUP BY sku ORDER BY SUM(number_of_orders) DESC LIMIT 0 , 10
) q
JOIN prod_combined ON prod_combined.sku = q.sku )
)
AND (aktiv = 1) LIMIT 5
有没有办法在一个查询中获得所需的结果?
亲切的问候, 最大
答案 0 :(得分:0)
内部查询在上个月内获得十个最畅销产品,但外部查询仅限制五个没有任何订购。如果将内部查询限制为5,则应该修复它。
以下是查询的加入版本:
SELECT `prod_combined`.`sku`, `prod_combined`.`titel`, `prod_combined`.`preis_vk`, `prod_combined`.`link`
FROM `prod_combined`
INNER JOIN `prod_history`
ON prod_combined.sku = prod_history.sku
WHERE prod_history.insert_date >= SUBDATE(CURDATE(), INTERVAL 31 DAY)
AND prod_combined.aktiv = 1
GROUP BY `prod_combined`.`sku`, `prod_combined`.`titel`, `prod_combined`.`preis_vk`, `prod_combined`.`link`
ORDER BY SUM(prod_history.number_of_orders) DESC
LIMIT 5
答案 1 :(得分:0)
我认为您的第二个查询中的活动顺序是关闭的...即您从产品开始然后对其进行限定。如果我要去那条路线,我会使用where not exists子句代替; x sku的计数大于我的产品计数不存在。
但是,您是否有理由不能将产品数据加入原始数据?
SELECT a.sku, a.titel, a.preis_vk, a.link, SUM(b.number_of_orders) as number_of_orders
FROM prod_combined as a inner join
prod_history as b on a.sku = b.sku
WHERE b.insert_date >= SUBDATE(CURDATE(), INTERVAL 31 DAY)
GROUP BY a.sku, a.titel, a.preis_vk, a.link
ORDER BY SUM(b.number_of_orders) DESC
LIMIT 0, 10
或沿着这些方向。