如何在MySQL中使用多行减去2个查询

时间:2016-07-25 04:22:52

标签: mysql

我想在这2个查询中减去每个prod_id的结果。

SELECT prod_id, prod_name, SUM(quantity) 
FROM purchasesdetails 
LEFT JOIN products ON (products._id=purchasesdetails.prod_id) 
GROUP BY prod_id

SELECT prod_id, prod_name, SUM(quantity) 
FROM notedetails 
LEFT JOIN products 
ON(notedetails.prod_id=products._id) 
GROUP BY prod_id

所以最后的结果是

|prod_name|SUM1-SUM2| 

prod_name在产品表中。

这是第一个查询的输出

prod_id | prod_name   | SUM(quantity)
176     | ANTIPIRINA  | 21
177     | BOMBAY      | 22

这是第二个查询的输出

prod_id | prod_name   | SUM(quantity)
176     | ANTIPIRINA  | 10
177     | BOMBAY      | 15

这是所需的输出

prod_id | prod_name   | sum1-sum2
176     | ANTIPIRINA  | 11
177     | BOMBAY      | 7

谢谢!

2 个答案:

答案 0 :(得分:4)

SELECT prod_id, prod_name, SUM(quantity) 
FROM purchasesdetails 
LEFT JOIN products ON (products._id=purchasesdetails.prod_id) 
GROUP BY prod_id where prod_in not in SELECT prod_id 
FROM notedetails 
LEFT JOIN products 
ON(notedetails.prod_id=products._id) 
GROUP BY prod_id

U可以不在子句中使用。

答案 1 :(得分:0)

对于这两个子查询,你可以这样做:

SELECT
    T1.prod_id, T1.prod_name, SUM(T1.quantity) AS `sum1-sum2`
FROM (
    SELECT prod_id, prod_name, SUM(quantity) AS quantity
    FROM purchasesdetails 
    LEFT JOIN products ON (products._id=purchasesdetails.prod_id) 
    GROUP BY prod_id
    UNION
    SELECT prod_id, prod_name, 0 - SUM(quantity) AS quantity
    FROM notedetails 
    LEFT JOIN products 
    ON(notedetails.prod_id=products._id) 
    GROUP BY prod_id
) T1
GROUP BY T1.prod_id, T1.prod_name

如果你的表products是主表,你也可以这样做:

SELECT n.prod_id, n.prod_name, SUM(p.quantity - n.quantity) AS quantity
FROM products 
LEFT JOIN notedetails n
ON products._id = n.prod_id
LEFT JOIN purchasesdetails p
ON p.prod_id = products._id
GROUP BY products._id