从左表中选择右表中不存在的所有记录

时间:2018-03-07 05:08:35

标签: stored-procedures sql-server-2012 left-join temp-tables isnull

我在sql服务器上工作我有两个表,我需要从左表返回记录,这些记录在右表中找不到,因为我正在使用左连接,如下面的查询,

select @MID=MID,@MName=Name,@PID=PID,@PName=PName,@DID=DID from @CompanyDataInfo where id=@MCount


insert into #temp SELECT  Top(1) f.Name,f.PID,f.PName,v.* FROM  @CompanyDataInfo f 
  left join  Employee v on  v.Id=f.ID and v.DID=f.DID 
  where  v.Id =@MID and v.DId = @DId and v.PId = @PId and v.CId =@CId and DATE_TIME between DATEADD(minute,-555,GETDATE()) and GETDATE() order by DATE_TIME desc 

结果应该是@CompanyDataInfo表中的所有行,而在Employee表中找不到相关ID的记录,我用Google搜索并使用" v.Id为null"但没有得到预期的结果

是否有任何解决方案非常适合

提前致谢

2 个答案:

答案 0 :(得分:0)

您的查询未正确使用left join。您在where子句中使用了正确的表引用。我尝试在下面更正它,但我没有关于您的表架构的完整信息。请试试这个 -

select
    @MID        = MID,
    @MName      = Name,
    @PID        = PID,
    @PName      = PName,
    @DID        = DID
from @CompanyDataInfo
where id = @MCount

insert into #temp
select
    f.Name,
    f.PID,
    f.PName,
    v.*
from @CompanyDataInfo f
left join  Employee v on v.Id=f.ID and v.DID=f.DID
where   f.Id = @MID and
        f.DId = @DId and
        f.PId = @PId and
        f.CId = @CId and
        f.DATE_TIME between DATEADD(minute,-555,GETDATE()) and GETDATE() and
        v.Id is null
order by f.DATE_TIME desc

答案 1 :(得分:0)

...and v.Id is null添加到您的where子句中。