2017-02-09 66 views
0

这里是我的代码...我自己测试了子查询,它起作用。我独自加入了两张桌子,这很有效。当我把它们合并时,我得到一个错误,指令没有正确结束。SQL代码与子查询连接表无法正常运行

select employees.last_name,departments.department_name,departments.location_id, locations.city 
FROM hr.employees, hr.departments, hr.locations 
where employees.department_id = departments.department_id 
AND departments.location_id = locations.location_id 
WHERE commission_pct = 
(select commission_pct 
from hr.employees 
where commission_pct IS NOT NULL) 
+0

commission_pct是单个值,但子查询返回一组结果。它有助于:'选择top 1 commission_pct'。另外,你可以复制/粘贴错误吗? –

+0

并将'WHERE commission_pct'更改为'AND commission_pct' – GurV

+0

哦,并且您有两个where子句。 –

回答

1

您的语法错误。我不知道你在用什么RDBMS,但至少你不能有两个WHERE子句 - 你应该使用AND而不是第二个WHERE。您也应该使用IN而不是=作为子查询,因为子查询可以返回多个结果,并且=会在失败时失败。

您还使用了不推荐的连接语法 - 您应该使用ANSI连接语法。例如。

select employees.last_name,departments.department_name,departments.location_id, locations.city 
FROM hr.employees 
INNER JOIN hr.departments 
ON employees.department_id = departments.department_id 
INNER JOIN hr.locations 
ON departments.location_id = locations.location_id 
WHERE commission_pct IN 
(select commission_pct 
from hr.employees 
where commission_pct IS NOT NULL) 

您可能还需要考虑做某种兑子查询,而不是一个WHEREJOIN,尽管这可能并不重要一样多。

+0

感谢IN语句的工作 –