我有兩個表。如何在SQL Server中查找某些條件不存在的記錄?
ItemRelation其表30K記錄
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
有上百萬條記錄
ItemID StoreId
-----------------
9 1001 //ItemID 9,41,5773 belongs to 1001 StoreID
41 1001
43 1400 //ItemID 43,45,65,5834 belongs to 1400 StoreID
45 1400
65 1400
68 2000 //ItemID 68,79 belongs to 2000 StoreID
79 2000
5773 1001
5834 1400
5838 2000
我想表明從ItemRelation表中的記錄ID F_ItemDailySalesParent在項目ID從F_ItemDailySalesParent在ItemRelation
不存在ItemID StoreID
-----------------
49 1001
111 1001
65 1001
222 1001
79 1001
9 1400
111 1400
222 1400
79 1400
9 2000
49 2000
111 2000
222 2000
5773 2000
我試過下面的q uery。但是,這將無需StoreID。但是,不知道對上述結果
select ID from HQMatajer.dbo.ItemRelation ir
where not exists(
select ID,StoreID
from [HQWebMatajer].[dbo].[F_ItemDailySalesParent] Fid
where fid.ItemID=ir.ID
or fid.ItemID = ir.ChildID1
or Fid.ItemID=ir.ChildID2
or Fid.ItemID=ir.ChildID3
and time between '2017-01-01 00:00:00.000' and '2017-02-28 00:00:00.000'
group by ItemID,StoreID
)
更新
我有一個的
storeCode = F_ItemDailySalesParent.Storeid
你在你的問題中的查詢是不正確的。 。 。至少,這是不太可能的,它有什麼用處。 –
@ PhamX.Bach是不同的。我的表中有重複的值。所以我應該做分組 –
@GordonLinoff是的,這是不正確的查詢,請注意我的問題上面的查詢。如果'F_ItemDailySalesParent'表中沒有'StoreID'字段。這將帶來不存在的記錄。 –