1

我需要在两个表上执行 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 操作,因为个人加入每个都会返回我的预期。一如既往地感谢任何帮助。

4

1 回答 1

0

这是执行以下操作的另一种方法full outer join

SELECT driver.country_iso2 AS country_iso2,
       g.total_given AS `total_given`,
       R.total_received AS `total_received`,
       driver.supersector AS `supersector` 
from ((select distinct country_iso2, supersector
       from giving_totals
      ) union
      (select distinct country_iso2, supersector
       from receiving_totals
      )
     ) driver left outer join
     giving_totals gt
     on gt.country_iso2 = driver.country_iso2 and
        gt.supersector = driver.country_iso2 left outer join
     receiving_totals rt
     on rt.country_iso2 = driver.country_iso2 and
        rt.supersector = driver.country_iso2

也就是说,将联合作为子查询来获取您感兴趣的所有组合。然后您可以left outer join对该表执行操作。

您的问题的原因是第二个查询中的别名。你可以试试这个:

SELECT r.country_iso2 AS country_iso2, g.total_given AS `total_given`,R.total_received    AS `total_received`,r.supersector AS `supersector` 
FROM (`giving_totals` `g` 
RIGHT JOIN `receiving_totals` `r` 
ON(((g.country_iso2 = r.country_iso2) 
AND (g.supersector = r.supersector)))) 

对于这些值,原始表单将具有 NULL。

于 2013-04-20T18:42:37.080 回答