我需要在两个表上执行 FULL OUTER JOIN,我正在尝试使用 LEFT JOIN/RIGHT JOIN/UNION ALL 技术在 MySQL 中实现它。
以下是原始表格:
giving_totals:
+--------------+---------------+-------------+
| country_iso2 | total_given | supersector |
+--------------+---------------+-------------+
| AE | 1396986989.02 | 3 |
| AE | 596757809.20 | 4 |
| AE | 551810209.87 | 5 |
| AE | 25898255.77 | 7 |
| AE | 32817.63 | 9 |
...
+--------------+---------------+-------------+
receiving_totals:
+--------------+----------------+-------------+
| country_iso2 | total_received | supersector |
+--------------+----------------+-------------+
| AE | 34759000.00 | 3 |
| AE | 148793.82 | 7 |
| AE | 734.30 | 9 |
| AF | 6594479965.85 | 1 |
| AF | 2559712971.26 | 2 |
+--------------+----------------+-------------+
我希望结果表为每个超级部门代码的每个国家/地区都有一个条目,即使它没有为该部门提供或收款(如果有人熟悉,这来自 AidData 项目数据集。)我想通过这样做来实现这一点LEFT JOIN(获取所有给予条目)和 RIGHT JOIN(获取所有接收条目)的 UNION。这是我尝试的查询:
SELECT g.country_iso2 AS country_iso2, g.total_given AS `total_given`,R.total_received AS `total_received`,g.supersector AS `supersector`
FROM (`giving_totals` `g`
LEFT JOIN `receiving_totals` `r`
ON(((g.country_iso2 = r.country_iso2)
AND (g.supersector = r.supersector))))
UNION ALL
SELECT g.country_iso2 AS country_iso2, g.total_given AS `total_given`,R.total_received AS `total_received`,g.supersector AS `supersector`
FROM (`giving_totals` `g`
RIGHT JOIN `receiving_totals` `r`
ON(((g.country_iso2 = r.country_iso2)
AND (g.supersector = r.supersector))))
但这只会返回第一个连接,无论我是先放置右连接还是左连接。我想我可能会误解 UNION 操作,因为个人加入每个都会返回我的预期。一如既往地感谢任何帮助。