将三张桌子连在一起

时间:2014-02-18 03:24:58

标签: sql sql-server outer-join

我有两张桌子可以正确加入。我试图引入第三个表,即使在特定年份没有数据我仍然想要null或0值。我的问题是,当我加入该表时,我得到重复记录或根本没有显示记录。

这是我尝试过的:

SELECT *
FROM [4th grade math achievement levels] m
  INNER JOIN [4th grade reading achievement levels] r
    ON m.Location = r.Location
      AND m.TimeFrame = r.TimeFrame
      AND m.[Achievement Level] = r.[Achievement Level]
  RIGHT OUTER JOIN [4th graders who scored below proficient reading level by geographic location] g
    ON m.Location = g.Location
      AND m.TimeFrame = g.TimeFrame
WHERE m.Location = 'ohio'
  AND m.TimeFrame = 2011

enter image description here

期望的结果 位置|成就等级|数据|地理位置|数据|大体时间 这就是我想要结合的东西 enter image description here

2 个答案:

答案 0 :(得分:2)

我很确定您需要left outer join而不是right outer join

SELECT * 
FROM [4th grade math achievement levels] m INNER JOIN
     [4th grade reading achievement levels] r 
     ON m.location = r.location AND
        m.timeframe = r.timeframe AND
        m.[achievement level] = r.[achievement level] LEFT OUTER JOIN
        [4th graders who scored below proficient reading level by geographic location] g 
        ON m.location = g.location AND
           m.timeframe = g.timeframe 
WHERE m.location = 'ohio' AND
      m.timeframe = 2011; 

left outer join会保留与条件匹配的mr表中的所有结果,为NULL中不存在g的值生成g比赛。在您的查询形式中,所有行都来自right outer join表(m)。但是,因为NULL表中的不匹配行将具有right outer join值,所以这些行将被过滤掉。结果是inner join真的表现得像{{1}}。

答案 1 :(得分:0)

您需要将where子句移动到连接中作为连接条件。当您在where子句中声明它时,强制查询删除Null

select *
from [4th grade math achievement levels] m
inner join [4th grade reading achievement levels] r
on m.Location = r.Location
    and m.TimeFrame = r.TimeFrame
    and m.[Achievement Level] = r.[Achievement Level] 
    and m.Location = 'ohio' -- old where clause
    and m.TimeFrame = 2011
right outer join [4th graders who scored below proficient reading level by geographic location] g
    on m.Location = g.Location
    and m.TimeFrame = g.TimeFrame