我有2张桌子。
第一个表存储产品。
id I Product Name
1 I Apple
2 I Bread
3 I Butter
... Many more
第二个表存储带有日期的整体购买
product_id I purchasedoverall I date
1 I 2 I 1.2.14
1 I 10 I 3.2.14
3 I 3 I 4.2.14
... Many more
注意:在这个例子中,出售的苹果为1.2.14 2个,另外还有3.2.14 8个苹果,因此有10个存储在buyoverall中。
我想从数据库中得到的是: 给我上周购买的产品,按上周购买的商品数量排序。
到现在为止,我这样做(不好):
我得到了所有产品
SELECT * FROM products
将它们存储在数组中
我迭代数组以获得上周购买的计数
SELECT MAX(c.purchasedoverall)-MIN(c.purchasedoverall) as purchased
FROM products as a, puchased as c
WHERE c.product_id = {product-id from the array}
AND c.date >= NOW() - INTERVAL 1 WEEK
ORDER BY c.date
我将数组组合起来
我的问题:我可以使用一个MySQL查询吗?
答案 0 :(得分:0)
假设pr.name
是唯一的:
SELECT pr.name,
COALESCE(MAX(pu.purchasedoverall)-MIN(pu.purchasedoverall),0) purchased
FROM products pr
LEFT JOIN purchased pu
ON pu.product_id = pr.id
AND pu.date > CURDATE() - INTERVAL 1 WEEK
GROUP BY pr.name
ORDER BY purchased DESC, pr.name
但正如评论中指出的那样,您应该真正以您需要的分辨率存储数据,而不是执行复杂的查询以提高分辨率。
无论获得数据结构和相关代码的困难是什么,重构这几乎肯定比在有缺陷的设计上构建系统容易得多。
答案 1 :(得分:0)
SELECT a.id, a.product_name, MAX(c.purchasedoverall)-MIN(c.purchasedoverall) as total_purchased
FROM products a
left join puchased c
ON c.product_id=a.id
AND c.date >= NOW() - INTERVAL 1 WEEK
group by a.id
ORDER BY total_purchased;