【问题标题】:select all records from left table that do not exist in right table从左表中选择右表中不存在的所有记录
【发布时间】:2018-03-07 05:08:35
【问题描述】:

我正在使用 sql server 我有两个表,我需要从左表返回在右表中找不到的记录,因为我正在使用如下查询的左连接,

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 的记录,我用谷歌搜索并使用“v.Id 为空”但没有得到预期的结果

有什么解决方法非常实用

提前致谢

【问题讨论】:

  • 当你用“sql”搜索你的标题时,你学到了什么?

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


【解决方案1】:

您的查询没有以正确的方式使用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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 是的,我使用了 'v.Id is null' 但它对我不起作用。
    猜你喜欢
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 2011-02-10
    相关资源
    最近更新 更多