MySQL UNION仅包括第一个表

时间:2013-04-20 18:34:21

标签: mysql left-join union right-join

我需要在两个表上执行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的UNION(获取所有给定条目)和RIGHT JOIN(获取所有接收条目)。这是我试过的查询:

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的操作,因为个人加入每个回归我的预期。任何帮助都会一如既往地受到赞赏。

1 个答案:

答案 0 :(得分: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

也就是说,将union作为子查询来获取您感兴趣的所有组合。然后,您可以对该表执行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。