我正在使用PHP和MySQL,我需要总结加入3个表的产品总数:
order_products:(表中有多个名称相同但金额不同的订单商品)
order_id (int)
product_name (varchar)
product_amount (int)
订单
order_id (int)
order_date (varchar)
order_status (varchar)
供应商:
product_name (varchar)
product_amount (int)
所以,我想展示我销售的产品数量和状态,以及我从供应商那里订购的产品数量。以下两个例子中的任何一个都将帮助我实现我的目标。
像:
Product Name (sum order_products) (sum supplier) Order status
first product 300 2500 Shipped_Only
second product 50 400 Shipped_Only
third product 10 600 Shipped_Only
Product Name (sum order_products) (sum supplier) Order status
first product 2200 2500 Not_Shipped
second product 400 400 Not_Shipped
third product 590 600 Not_Shipped
我可以做任何示例或其他帮助吗?
编辑: 样本数据就像这样
order_products:
order_id product_name product_amount
255 product 1 200
256 product 1 100
257 product 2 50
258 product 3 10
订单: order_id order_date order_status
255 09.05.2018 Shipped
256 09.05.2018 Shipped
257 10.05.2018 Not_Shipped
258 10.05.2018 Not_Shipped
供应商: product_name product_amount
product 1 2500
product 2 400
product 3 600
答案 0 :(得分:2)
您应该在聚合子选择上使用联接。
SELECT t1.product_name, t1.sum_order_products, t2.supplier_sum, t1.order_status
FROM (
SELECT op.product_name, SUM(op.product_amount) sum_order_products, o.order_status
FROM order_products op
INNER JOIN orders o ON op.order_id = o.order_id
WHERE o.order_status = 'Shipped'
GROUP BY op.product_name, o.order_status
) t1
LEFT JOIN (
SELECT s.product_name, SUM(s.product_amount) supplier_sum
FROM supplier s
GROUP BY s.product_name
) t2 ON t1.product_name = t2.product_name
ORDER BY t1.order_status, t1.product_name
答案 1 :(得分:1)
根据我的理解,我认为这就是你想要的,如果这不是你所期望的,请更清楚。
您将需要使用GROUP BY子句,您必须使用count()函数来计算来自Group By Clause的结果的行数。我正在编写一个如何使用group by子句的示例,您需要根据需要修改查询。
SELECT
order_products.product_name,
count(*) as Total_Orders,
MAX(supplier.product_amount) as Supplier_Amt,
orders.order_status
FROM supplier
INNER JOIN order_products ON supplier.product_name = order_products.product_name
INNER JOIN orders ON orders.order_id = order_products.order_id
WHERE orders.order_status = 'Not_Shipped'
GROUP BY order_products.product_name, orders.order_status;
您需要查询,您可以编写另一个查询,只需将WHERE orders.order_status = 'Not_Shipped'
替换为WHERE orders.order_status = 'Shipped'
此外,如果您想要在一个查询中完成所有操作,只需删除where子句。