SQL代码无法正常运行以连接具有子查询的表

时间:2017-02-09 17:25:50

标签: 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)

1 个答案:

答案 0 :(得分:1)

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

您还使用了不推荐使用的连接语法 - 您应该使用ANSI连接语法。 E.g。

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)

您可能还想考虑针对子查询而不是JOIN执行某种WHERE,尽管这可能并不重要。