Northwind数据库| SQL查询返回员工和他们报告给谁

问题描述:

我想写一个罗斯文数据库的查询列出雇员和他们的经理的名字,没有包括没有人报告的员工。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

你应该尝试:

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

非常感谢! –

比较尝试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分钟内击败了你,但我非常感谢你的帮助!如果我可以选择多个答案,我绝对会,但再次感谢! :) –

我明白了,永远不会尝试将值与空值进行比较。正确的答案是:

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

只有当您设置查询选项“SET ANSI_NULLS”为OFF时,您才可以使用'='或''('!=')与'NULL'进行比较 – LONG