我有以下表格:
几何学
| ID | GEOID | YEAR | VALUE |
| 1 | 100 | 2010 | 76 |
| 2 | 100 | 2020 | 1 |
| 3 | 101 | 2010 | 73 |
| 4 | 101 | 2020 | 123 |
| 5 | 102 | 2010 | 4 |
| 6 | 102 | 2020 | 20 |
年
| YEAR |
| 2010 |
| 2020 |
地区
| ID | GEOID | REGION |
| 1 | 100 | 1 |
| 2 | 101 | 1 |
| 3 | 102 | 1 |
| 4 | 100 | 2 |
| 5 | 101 | 2 |
| 6 | 102 | 3 |
我想获得大地水准面、年份和区域 = 2 的值。这是我的 SQL:
SELECT DISTINCT reg.geoid, years.year, j.value
FROM regions AS reg, years
LEFT JOIN (
SELECT geometry.geoid, geometry.year, geometry.value
FROM geometry
JOIN regions AS reg
ON reg.geoid = geometry.geoid
AND reg.region = 2
) AS j
ON j.year = years.year
WHERE reg.region = 1
AND reg.geoid = j.geoid
这给了我这个:
| GEOID | YEAR | VALUE |
| 100 | 2010 | 76 |
| 100 | 2020 | 1 |
| 101 | 2010 | 73 |
| 101 | 2020 | 123 |
但我想得到所有的大地水准面和所有年份。这就是我执行 LEFT JOIN 的原因,以便它返回 LEFT 表的所有行。我希望它会返回这个:
| GEOID | YEAR | VALUE |
| 100 | 2010 | 76 |
| 100 | 2020 | 1 |
| 101 | 2010 | 73 |
| 101 | 2020 | 123 |
| 102 | 2010 | null |
| 102 | 2020 | null |
我怎样才能做到这一点?
更新
这是上述数据的 SQLFiddle:http ://sqlfiddle.com/#!2/963c7/6