2017-04-17 34 views
0

我想寫一個羅斯文數據庫的查詢列出僱員和他們的經理的名字,沒有包括沒有人報告的員工。Northwind數據庫| SQL查詢返回員工和他們報告給誰

這是我到目前爲止有:

SELECT employees.firstname, employees.lastname, superior.firstname, superior.lastname 
FROM employees 
LEFT OUTER JOIN employees superior ON employees.reportsto = superior.employeeID 
WHERE employees.reportsto <> null; 

這個查詢運行,但似乎什麼都沒有。

+0

對不起,檢查和取消選中你們的答案按鈕反覆!我認爲我可以選擇多個答案。 –

+0

今天提示:爲兩個員工實例聲明表別名,以使代碼更清晰。 – jarlh

回答

0

你應該嘗試:

SELECT employees.firstname, employees.lastname, superior.firstname, superior.lastname 
FROM employees 
LEFT OUTER JOIN employees superior ON employees.reportsto = superior.employeeID 
WHERE employees.reportsto IS NOT NULL --or "<> NULL" when ANSI_NULLS is set to OFF ("!=" is specific to SQL server) 

如果使用sql server,默認是set ANSI_NULLS上,則需要使用IS/IS NOTNULL

+0

這是關於**沒有**包括員工誰沒有人報告,所以它應該是非零 –

+0

@RandikaRatnayake,我的壞視力 – LONG

+0

非常感謝! –

0

比較嘗試IS NOT NULL

SELECT employees.firstname, employees.lastname, superior.firstname, superior.lastname 
FROM employees 
LEFT OUTER JOIN employees superior ON employees.reportsto = superior.employeeID 
WHERE employees.reportsto IS NOT NULL; 

說明: NULL沒有值,因此不能使用標量值運算符進行比較。 https://stackoverflow.com/a/5658472/684030

+0

非常感謝! –

+0

快樂。標記爲答案,如果有幫助:) –

+0

對不起!另一個人在4分鐘內擊敗了你,但我非常感謝你的幫助!如果我可以選擇多個答案,我絕對會,但再次感謝! :) –

0

我明白了,永遠不會嘗試將值與空值進行比較。正確的答案是:

WHERE employeesAM.reportsto **is not** null; 
+0

只有當您設置查詢選項「SET ANSI_NULLS」爲OFF時,您纔可以使用'='或'<>'('!=')與'NULL'進行比較 – LONG