我想知道我做对了什么。
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%');
- 您希望显示
Department Number
和Department Name
的不同值 -
Department Number
上的Employees
表与Department
表合并 -
Job ID
上Employees
和Jobs
表的连接 - 通过排除整个
Employee
表中具有匹配模式%SA_REP%
的Job ID
的Department Numbers
来过滤结果
在我看来你不需要
- 与
Jobs
表的连接 - 连接
Employees
表 - 你也许可以看看其他用户的建议是否可以带来性能改进
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%'
);
您可以简单地使用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);
可以翻译没有"in"的where条件。你不需要从"Jobs"中获取日期——你不用它
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%';