2 つのテーブルで 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 |
+--------------+----------------+-------------+
結果のテーブルには、スーパーセクター コードごとに国ごとに 1 つのエントリが含まれている必要があります (そのセクターに対して金銭を授受していない場合でも) (これは、誰かがよく知っている場合に備えて、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 操作を誤解している可能性があると思います。なぜなら、個人が参加するたびに、私が期待したものが返されるからです。いつものようにどんな助けでも大歓迎です。