我需要在兩個表上執行FULL OUTER JOIN,我正試圖在MySQL中使用LEFT JOIN/RIGHT JOIN/UNION ALL技術來實現它。MySQL UNION只包括第一個表
這裏是原始表:
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項目數據集的情況下,任何人都很熟悉。)我想通過做一個左連接(獲得所有給予條目)和右連接(獲取所有接收條目)的聯合來完成此操作。以下是我嘗試的查詢:
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))))
但是這隻返回第一個jo無論我是否先將右側或左側連接起來。我想我可能會誤解UNION的運作,因爲每個人的加入都會返回我的預期。任何幫助一如既往地受到讚賞。
在第二次選擇工會時使用您加入的表中的表別名,否則您將獲得NULL country_iso2和supersector。如果您不想查看包含給定和接收兩次的行,請使用UNION而不是UNION ALL。除此之外,查詢沒有任何問題。 – piotrm 2013-04-20 22:28:14