2017-04-26 83 views
1

我試圖從兩個表中選擇SUMed數據。 這是他們的樣子。Mysql從兩個表中選擇兩個SUM

表1:

products | revenue| 
------------------| 
product1 | 10  | 
product2 | 20  | 
product1 | 20  | 

表2:

products | revenue| 
------------------| 
product1 | 40  | 
product2 | 30  | 
product2 | 40  | 

所以查詢應該總結他們是這樣的:

products | revenue| 
------------------| 
product1 | 70  | 
product2 | 90  | 

我已經試過這和其他一些疑問,但他們不正確。

SELECT Table1.products, Table1.SUM(`revenue`), Table2.SUM(`revenue`) 
FROM Table1 
JOIN Table2 
ON  Table1.products = Table2.products 
group by Table1.products; 

你能幫幫我,在這種情況下什麼是正確的查詢?謝謝。

回答

1

使用UNION ALL和SUM聚合函數:

SELECT products , SUM(revenue) revenue 
FROM 
(
    SELECT products , revenue 
    FROM table1 
    UNION ALL 
    SELECT products , revenue 
    FROM table2 
) A 
GROUP BY products 
+0

謝謝你,你的回答更正確。 – Geobo

2

我會建議使用union all然後group by

select product, sum(revenue) 
from ((select product, revenue from table1) union all 
     (select product, revenue from table2) 
    ) tt 
group by product; 

這將確保所有的產品都在結果集中,即使是隻在一個表中的產品。

+0

真棒。有用。謝謝。 – Geobo