我很难处理多个表格。我希望每周都能获得所有订单的产品总数。 我使用了以下代码:
$sql = "SELECT id_order, order_placed FROM orders
WHERE YEAR(order_placed) = YEAR(NOW())
AND WEEKOFYEAR(order_placed) = WEEKOFYEAR(NOW())";
以上查询将返回当前周的所有订单。然后我添加了一个新的SQL查询,以从检索到的ID订单中获取所有产品ID。
$sql2 = "SELECT id_product, COUNT(id_product) AS num_products
FROM order_product
WHERE id_order = '".$id_order."'";
$results2 = Db::getInstance()->ExecuteS($sql2);
以同样的方式我获得了其他信息。当我打印最终陈述时,它将像:
Order ID: 1, Date: 06/07/2015, Product: 100052, Name: Example A
Order ID: 1, Date: 06/07/2015, Product: 100052, Name: Example A
Order ID: 2, Date: 07/07/2015, Product: 9987, Name: Example B
但我想找到一种方法来显示总数:
Order ID: 1, Date: 06/07/2015, Product: 100052, Name: Example A, Count: 2
Order ID: 2, Date: 07/07/2015, Product: 9987, Name: Example B, Count: 1
此外,我会按周对它们进行分组,因此每行只包含当前周的信息。
下面你可以看到表格以获得一个想法(为了方便你,我会简化它们)
订单
-----------------------------------
| Order ID | Date |
-----------------------------------
| 1 | 06/07/2015 15:20:01 |
-----------------------------------
| 2 | 07/07/2015 10:10:41 |
-----------------------------------
ORDER_PRODUCTS
------------------------------------------
| Order ID | Product ID | Product Type |
------------------------------------------
| 1 | 10052 | 1 |
------------------------------------------
| 1 | 10052 | 1 |
------------------------------------------
| 2 | 9987 | 0 |
------------------------------------------
客户可以根据需要订购尽可能多的产品。这就是为什么上表包含两次10052 ID的原因。例如,该客户两次订购10052。 另外,我只想要输入' 1'被检索。
PRODUCT_ID_NAME
------------------------
| Product ID | ID Name |
------------------------
| 10052 | 1 |
------------------------
| 9987 | 2 |
------------------------
产品名称
--------------------------
| ID Name | Product Name |
--------------------------
| 1 | Example_A |
--------------------------
| 2 | Example_B |
--------------------------
任何人都可以帮我吗? 目标是显示每周销售的产品数量。
Week 1: Example A sold: 150, Example B sold: 15
Week 2: Example A sold: 100, Example B sold: 50
etc
答案 0 :(得分:2)
GROUP_BY
是你的朋友。
我不确定您的表名或列名,但这应该可以帮助您:
SELECT o.order_id, o.order_placed, op.product_id, pn.product_name, COUNT(op.order_id) AS `count`
FROM `orders` o
INNER JOIN `order_products` op ON op.order_id = o.id
INNER JOIN `product_id_name` pin ON pin.product_id = op.product_id
INNER JOIN `product_name` pn ON pn.id_name = pin.id_name
WHERE YEAR(o.order_placed) = YEAR(NOW())
AND WEEKOFYEAR(o.order_placed) = WEEKOFYEAR(NOW())
GROUP BY op.order_id
[编辑] Ak,这会让你进入
Order ID: 1, Date: 06/07/2015, Product: 100052, Name: Example A, Count: 2
Order ID: 2, Date: 07/07/2015, Product: 9987, Name: Example B, Count: 1
我没有看到关于按产品分组的一点 - 但这更像是一回事。只需按产品ID分组,而不是订单ID。