合并加入错误输出(完全外连接)

时间:2015-04-09 16:34:59

标签: sql-server join

我有合并加入问题。我有两张桌子要加入:

table1:

year , environment , population with values 
------------------------------------------    
2000 , rural , x1     
2000, urbain , x2     
2005, rural , x3 ...etc 

table2:

year , environment , poverty_rate
---------------------------------
2000 , rural , y1     
2000, urbain , y2     
2005, ... etc

我进行了合并连接转换(完全外连接),输出类似于:

year, environment, population, poverty_rate 
-------------------------------------------
2005 , rural , x3 , NULL     
2005 , urbain, x4, y4     
NULL, NULL, NULL , y3

有人可以帮我找出这个问题吗?我做错了什么?

1 个答案:

答案 0 :(得分:0)

假设年份和环境是1和2彼此相同的列,并且假设您只想在这两个值匹配时显示人口和贫困率,那么您可能想尝试这样:

SELECT t1.year, t1.environment, t1.population, t2.poverty_rate
FROM table1 as t1
INNER JOIN table2 as t2 ON t1.year = t2.year AND t1.environment = t2.environment

如果你想要table1中的所有记录,只有那些与table2匹配的记录,试试这个:

SELECT t1.year, t1.environment, t1.population, t2.poverty_rate
FROM table1 as t1
LEFT JOIN table2 as t2 ON t1.year = t2.year AND t1.environment = t2.environment