如何根据外键从两个表中检索两个SUM()值并减去它们

时间:2017-09-27 11:58:02

标签: mysql sql

我有3张桌子

products table purchase table sale table
+----+---------+ +----+-----------+-------+ +----+------------+--------+ | id | product | | id | product_id| pieces| | id | product_id | pieces | +----+---------+ +----+-----------+-------+ +----+------------+--------+ | 1 | Tyre | | 1 | 3 | 5 | | 1 | 2 | 3 | +----+---------+ +----+-----------+-------+ +----+------------+--------+ | 2 | Switch | | 2 | 1 | 3 | | 2 | 1 | 2 | +----+---------+ +----+-----------+-------+ +----+------------+--------+ | 3 | Ring | | 3 | 2 | 6 | | 3 | 3 | 3 | +----+---------+ +----+-----------+-------+ +----+------------+--------+ | 4 | Wheel | | 4 | 3 | 4 | | 4 | 2 | 1 | +----+---------+ +----+-----------+-------+ +----+------------+--------+

  1. 我想基于/ GROUP BY product_id在购买表和销售表中SUM()两个部分列。 Ex- SELECT products, SUM(pieces) FROM purchase GROUP BY product_id相同的销售表查询。

  2. 我想减去SUM()结果以找出剩余的部分。前 - SUM(purchase.pieces) - SUM(sale.pieces) AS balance

  3. 最后我需要产品表中的产品名称,购买表中的相同产品的总数,这意味着产品已经销售了多少次如轮胎 - 5件,同样的销售表,以及之后的剩余件从产品的总购买量中减去产品的总销售额。

  4. 如何使用PHPPDO

    执行此操作

2 个答案:

答案 0 :(得分:0)

您可以对件列使用SUM(),并获得差异以获得余额

SELECT p.id,
       p.product,
       IFNULL(total_purchase,0) total_purchase,
       IFNULL(total_sales,0) total_sales,
       IFNULL(total_purchase,0) - IFNULL(total_sales,0) balance
  FROM (SELECT pd.id,
               pd.product,
               SUM(pc.pieces) total_purchase
          FROM products pd
          LEFT JOIN purchase pc
            ON pd.id = pc.product_id
         GROUP BY pd.id, pd.product
       ) p
  JOIN (SELECT pd.id,
               pd.product,
               SUM(sl.pieces) total_sales
          FROM products pd
          LEFT JOIN sales sl
            ON pd.id = sl.product_id
         GROUP BY pd.id, pd.product
       ) s
    ON p.id = s.id
 ORDER BY p.id

Result

id  product total_purchase  total_sales balance
1   Tyre    3               2           1
2   Switch  6               4           2
3   Ring    9               3           6
4   Wheel   0               0           0

答案 1 :(得分:-1)

这样的事情应该是一个好的开始:

select 
products.product
purchases.Total as PurchasedPieces,
sales.Total as SoldPieces
purchases.Total - sales.Total as balance
from
products
left join (select(product_id,SUM(pieces) as Total from purchases group by product_id)) purchases on products.id = purchases.product_id
left join (select(product_id,SUM(pieces) as Total from sales group by product_id)) sales on products.id = sales.product_id