这个SQL语句看起来正确吗?
我想知道我做对了什么这个SQL语句看起来正确吗?,sql,Sql,我想知道我做对了什么 select distinct Departments.Department_No, Departments.Department_Name from Departments join Employees on Departments.Department_No = Employees.Department_No join Jobs on Jobs.Job_ID = Employees.Job_ID where Dep
select distinct
Departments.Department_No, Departments.Department_Name
from
Departments
join
Employees on Departments.Department_No = Employees.Department_No
join
Jobs on Jobs.Job_ID = Employees.Job_ID
where
Departments.Department_No not in (select distinct Department_No
from Employees
where Employees.Job_ID like '%SA_REP%');
您可以在没有输入的情况下转换where条件。 而且你不需要从工作中获取日期——你不需要使用它
Select distinct Departments.Department_No, Departments.Department_Name
from Departments
Join Employees on Departments.Department_No = Employees.Department_No
where Employees.Job_ID not like '%SA_REP%';
您只需使用NOT EXISTS而不是NOT IN子查询即可:
SELECT DISTINCT
d.Department_No
,d.Department_Name
FROM Departments d
JOIN Employees e ON d.Department_No = e.Department_No
WHERE NOT EXISTS
(select 1
from Employees e1
where e1.Job_ID like '%SA_REP%'
AND e1.Department_No = e.Department_No);
您希望显示部门编号和部门名称的不同值
将员工表与部门号上的部门合并
您可以使用工作ID上的员工加入工作表
您可以通过排除整个员工表中具有与模式%SA_REP%匹配的职务ID的部门号来过滤结果
在我看来,你不需要
与Jobs表的联接
连接到Employees表
您可能会看到其他用户的建议之一是否可以带来性能改进
您正在使用哪些RDBMS?你想要什么结果?你试过执行它吗?它给你正确的结果吗?你特别关心什么?为什么你加入员工和工作,但不使用他们的任何列?这改变了语义。如果OP中有任何员工的职务ID为“%SA_REP%”,则OP中的查询不会返回部门-除非所有员工都符合该条件,否则仍会返回部门。@Martin Smith我想你是对的。我不这么认为。我已更新我的解决方案以使用“不存在”。
SELECT DISTINCT departments.department_no,
departments.department_name
FROM departments
WHERE departments.department_no NOT IN (SELECT DISTINCT department_no
FROM employees
WHERE employees.job_id LIKE '%SA_REP%'
);