2016-10-06 37 views
-6

我有兩個結果:如何加入兩個MySQL結果轉換成一個?

- | month  | first_time_buyers | 
- | 2016-07-01 |     2 | 
- | 2016-08-01 |     2 | 

- | month  | returned_buyers | 
- | 2016-08-01 |    1 | 
- | 2016-09-01 |    2 | 

我想將它們連接成一個結果,如:

- | date  | first_time_buyers | returned_buyers | 
- | 2016-07-01 |     2 |    0 | 
- | 2016-08-01 |     2 |    1 | 
- | 2016-09-01 |     0 |    2 | 
+4

你怎麼能指望我們來幫助你?顯示您的查詢,數據和表格。 – HoneyBadger

+0

請格式化您的文本。 :( –

+0

是兩個不同的表,你是怎麼認識的買家(ID爲)? –

回答

0

由於在MySQL的沒有FULL JOIN,你需要使用UNION ALL兩個連接查詢在外部查詢中使用group by。

SELECT month, 
     first_time_buyers, 
     returned_buyers 
FROM (SELECT table1.month, 
       Ifnull(first_time_buyers, 0) AS first_time_buyers, 
       Ifnull(returned_buyers, 0) AS returned_buyers 
     FROM table1 
       LEFT JOIN table2 
         ON table1.month = table2.month 
     GROUP BY month 
     UNION ALL 
     SELECT table2.month, 
       Ifnull(first_time_buyers, 0) AS first_time_buyers, 
       Ifnull(returned_buyers, 0) AS returned_buyers 
     FROM table2 
       LEFT JOIN table1 
         ON table2.month = table1.month 
     GROUP BY month) t 
GROUP BY month; 
+0

能你給我一個查詢,請 – ngunq

+0

編輯我的答案。看一看吧。 – Jayaprakash

+0

它是否幫助?如果有幫助,請接受我的回答。 – Jayaprakash

相關問題