代码之家  ›  专栏  ›  技术社区  ›  geoff swartz

不在其他表中的SQL Server查询

  •  1
  • geoff swartz  · 技术社区  · 6 年前

    我有三张桌子:

    乔布斯

        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 回复  |  直到 6 年前
        1
  •  5
  •   M.Ali    6 年前
    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%'
                    ) 
    
        2
  •  -1
  •   Paulo Roberto Elias    6 年前

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