2014-02-18 87 views
1

我有兩張表,能夠正確加入。我試圖引入第三個表格,即使在特定年份沒有數據,我仍然希望爲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

+0

用戶LEFT OUTER JOIN來比較你的價值,你會得到一個結果,然後你可以決定你堅持你沒有能提供足夠的信息。這裏 –

+0

同意了,右外連接是你的問題。 – mikey

+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表匹配條件,生成NULLg中的值不匹配。在查詢的形式中,所有行均來自g表(right outer join)。但是,由於m表中的不匹配行將具有NULL值,因此這些值將被濾除。結果是right outer join確實表現得像inner join

0

您需要將where子句移動到您的連接中作爲連接條件。當你在where子句中陳述它,你強制查詢砸空值

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 
+0

這加入了所有表格,但在前兩個表格中創建了重複項目。 –

+0

然後第三個表中的每一行都有一個鏈接返回到前兩個表中的一個表中的兩行。關於您的數據如何關聯,還有一些尚未向我們闡明。第三張桌子是以人爲本的,對嗎?所以你的右外連接是故意的,對嗎?表3中的每個學生是否有可能在數學上相應的排和在閱讀中有相應的排? – wruckie

+0

除非每個時間範圍和地點只有一名學生,否則在必要時會重複使用表格。你可以發佈一個輸出樣本嗎? – wruckie