我有两个结果:
- | 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 |
答案 0 :(得分: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;