2011-04-30 91 views
3

該示例已簡化。我有以下設計: http://img835.imageshack.us/i/designyi.jpg/使用基本的sql查詢幫助

我已經插入這樣的測試數據:

INSERT INTO Period VALUES ('Survey for 2011', 1) 

INSERT INTO EvalQuestion VALUES('How do...') 
INSERT INTO EvalQuestion VALUES('How many...') 
INSERT INTO EvalQuestion VALUES('Which is....') 

INSERT INTO EvalQuestion_Period VALUES (1, 1) 
INSERT INTO EvalQuestion_Period VALUES (1, 2) 
INSERT INTO EvalQuestion_Period VALUES (1, 3) 

INSERT INTO Employee VALUES ('Peter', 'Smith') 
INSERT INTO Employee VALUES ('Britney', 'Spears') 

INSERT INTO EvalAnswer VALUES(1,'Fine',1) 
INSERT INTO EvalAnswer VALUES(2,'45',1) 
INSERT INTO EvalAnswer VALUES(3,'I don´t know',1) 
INSERT INTO EvalAnswer VALUES(1,'Fine again',2) 
INSERT INTO EvalAnswer VALUES(2,'45 again',2) 
INSERT INTO EvalAnswer VALUES(3,'I don´t know again',2) 

我運行下面的查詢來獲取問題和答案彼得:

Select Name, Answer 
from EvalQuestion eq 
LEFT JOIN EvalQuestion_Period eqp ON eq.Id = eqp.FK_EvalQuestion 
LEFT JOIN EvalAnswer ea ON ea.FK_EvalQuestion_Period = eqp.Id 
where ea.FK_Employee = 1 

結果集:

Name   Answer 
----------------------- 
How do...  Fine 
How many... 45 
Which is.... I don´t know 

這看起來不錯。如果我刪除彼得斯的一個答案是這樣的:

Delete from EvalAnswer where ID= 1 

,並運行相同的查詢,我只得到兩行,像這樣

Name   Answer 
----------------------- 
How many... 45 
Which is.... I don´t know 

我需要我的問題的結果,即使設置爲只要是懸而未決,像這樣:

Name   Answer 
----------------------- 
How do....  NULL 
How many... 45 
Which is.... I don´t know 

任何提示?謝謝

回答

0

你的「左連接」實際上是一個LEFT OUTER JOIN(儘管其他答案):連接類型由LEFTRIGHTOUTER是可選

當您使用WHERE ea.FK_Employee = 1那麼你改變這個到內暗含加入,因爲你不允許缺少行。您需要首先進行過濾(即在加入前限制EvalAnswer上的行)。這是因爲WHERE在JOIN..ON邏輯後處理。

與派生,過濾表試試這個:

Select Name, Answer 
from EvalQuestion eq 
LEFT JOIN 
EvalQuestion_Period eqp ON eq.Id = eqp.FK_EvalQuestion 
LEFT JOIN 
     (SELECT * FROM EvalAnswer 
     where FK_Employee = 1 
     ) ea ON ea.FK_EvalQuestion_Period = eqp.Id 

或是在條件進行過濾:

Select Name, Answer 
from EvalQuestion eq 
    LEFT JOIN 
    EvalQuestion_Period eqp ON eq.Id = eqp.FK_EvalQuestion 
    LEFT JOIN 
    EvalAnswer ea ON ea.FK_EvalQuestion_Period = eqp.Id AND ea.FK_Employee = 1 
+0

嗨gbn。謝謝你,兄弟。看起來這是我需要的。我想你的意思是在最後一行:eqp.Id AND ea.FK_Employee = 1.它按預期工作。再次感謝...... – Cliff 2011-04-30 15:37:37

+0

@懸崖:是的,更正了,謝謝 – gbn 2011-04-30 15:38:34

0

任何時候你想從原始表中返回一行或多行,你可以使用外連接。所以,你的查詢是:

Select Name, Answer 
    from EvalQuestion eq 
     LEFT JOIN EvalQuestion_Period eqp ON eq.Id = eqp.FK_EvalQuestion 
     LEFT OUTER JOIN EvalAnswer ea ON ea.FK_EvalQuestion_Period = eqp.Id 
    where ea.FK_Employee = 1 

這將返回空值從EvalAnswer值時,沒有相應的記錄存在,否則會正好充當LEFT JOIN。

+0

-1,因爲這應該沒有給予好評。 1「OUTER」是可選的2 WHERE將其更改爲* inner * join。 – gbn 2011-04-30 15:29:32

+0

是的,我應該多加考慮一下。爲了清晰起見,我總是使用'outer',並且我忘記了它是可選的。 – Kendrick 2011-05-03 15:58:10