在我的情况下如何在SQL Server中使用NOT EXISTS?

时间:2017-03-26 07:11:27

标签: sql sql-server tsql stored-procedures

我想从一个表中检索一些不存在于另一个表中的数据。

#tempLastSold表记录(实际记录3000)

ItemID
------
9
41
43
45
65
68
79
5773
5834
5838

ItemRelation表记录(实际记录30,000)

ID     ChildID1     ChildID2     ChildID3
------------------------------------------
9      null         null          null
49     43           50                       //43 in childid1, don't want this record too
111    112          113           null
65     68           null          null
222    221          223           224
79     null         null          null
5773   5834         5838          null

我想从ItemRelation表记录中获取记录,该记录不包含#tempLastSold

中任何字段中的任何值

预期产出:

ID     ChildID1     ChildID2     ChildID3
------------------------------------------
111    112          113           null
222    221          223           224

我试过这个

select id 
from ItemRelation
where not exists (select ir.id 
                  from ItemRelation ir
                  inner join #tempLastSold ls on ls.ItemID = ir.ID 
                                              or ls.ItemID = ir.ChildID1
                                              or ls.ItemID = ir.ChildID2
                                              or ls.ItemID = ir.ChildID3)

我不确定我的查询是正确还是错误。但它仍然加载并且它跨越3分钟

但它继续加载。因为Itemrelation表有30K记录。但我认为这是非常少的记录

2 个答案:

答案 0 :(得分:3)

您必须在没有内部联接的情况下使用NOT EXISTS,建议使用NOT INLEFT JOIN / IS NULLNOT IN vs. NOT EXISTS vs. LEFT JOIN / IS NULL: SQL Server

select id 
from ItemRelation ir
where not exists (
select 1
from  #tempLastSold ls 
WHERE ls.ItemID in (ir.ID, ir.ChildID1, ir.ChildID2, ir.ChildID3)
) AND ir.id is NOT NULL

答案 1 :(得分:2)

试试这个,works on your sample data

select ir.*
from ItemRelation ir 
left join #tempLastSold t1 on ir.ID = t1.ItemID
left join #tempLastSold t2 on ir.ChildID1 = t2.ItemID
left join #tempLastSold t3 on ir.ChildID2 = t3.ItemID
left join #tempLastSold t4 on ir.ChildID3 = t4.ItemID
where t1.ItemID is null and t2.ItemID is null and t3.ItemID is null and t4.ItemID is null