这个SQL语句看起来是否合适?

时间:2015-07-29 16:26:38

标签: 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  
    Departments.Department_No not in (select distinct Department_No 
                                      from Employees 
                                      where Employees.Job_ID like '%SA_REP%');

3 个答案:

答案 0 :(得分:2)

您可以使用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);

答案 1 :(得分:2)

  • 您希望显示Department NumberDepartment Name
  • 的不同值
  • 您在Employees
  • 加入Department表与Department Number
  • 您在Jobs
  • 加入Employees表与Job ID
  • 您可以通过排除{em>整个 Department NumbersEmployeeJob ID匹配模式%SA_REP%

在我看来,你不需要

  • 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%' 
                                        ); 

答案 2 :(得分:1)

您可以在没有“in”的情况下翻译条件。 而且您不需要从“作业”中获取日期 - 您不使用它

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%';