2016-07-25 47 views
3

我想在這2個查詢中減去每個prod_id的結果。如何在MySQL中減去多行中的2個查詢

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 

謝謝!

+0

顯示一些樣本數據和請期待結果。 – Blank

+0

我想對每行(產品)進行操作 – Padiller

回答

3
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可以在條款中使用。

+0

我想對每行(產品)進行操作 – Padiller

+0

此操作執行您所要求的操作 - 它對兩個表中prod_id匹配的每一行執行計算。 –

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 
+0

這工作!謝謝。 – Padiller