SQL Server查询不在其他表中

时间:2018-08-03 12:56:44

标签: sql sql-server

我有三个表:

工作

    JobId
    StartDate
    RehireDate

文书工作

    PaperworkId
    DocumentName

工作文件

    JobId
    PaperworkId
    Completed

我需要找到没有分配给具有特定文档名称的文档的所有作业。我不确定如何构造此查询。使用NOT IN不起作用,因为它会查找到分配有其他文书工作的工作,因此会返回所有工作。

这就是我的开始:

select j.jobid 
from Job j 
inner join JobPaperwork jp on j.JobId = jp.JobID 
where j.startdate > dateadd(day, -30, getdate()) 
  and j.rehiredate is not null 
  and jp.PaperworkID not in (select paperworkid 
                             from Paperwork 
                             where documentname like '%searchterm%') 

2 个答案:

答案 0 :(得分:5)

select j.jobid 
from Job j 
inner join JobPaperwork jp on j.JobId = jp.JobID 
where j.startdate > dateadd(day, -30, getdate()) 
and j.rehiredate is not null 
and NOT EXISTS ( select 1 
                 from Paperwork pw 
                 where jp.PaperworkID = pw.paperworkid
                 and pw.documentname like '%searchterm%'
                ) 

答案 1 :(得分:-1)

您可以使用NOT EXISTS语句,如下所示:

select j.jobid 
from Job j 
inner join JobPaperwork jp on j.JobId = jp.JobID 
where j.startdate > dateadd(day, -30, getdate()) 
and j.rehiredate is not null 
and jp.PaperworkID not exists (
select 1 
from Paperwork 
where 
documentname like '%searchterm%'
)