我有三個表,如下所述:SQL NOT EXISTS條件
dbo.ServiceEntry
ID RunLogEntry Reconciled
1 0 1
2 4 1
3 5 1
dbo.ServiceEntryPart
ID ServiceEntryID PartId ServiceEntryTypeID
1 1 3 1
2 2 4 2
3 2 4 1,2
dbo.Part
ID Desc Active (bitfield)
3 xyz 1
4 abc 1
查詢,如下所示:
SELECT *
FROM ServiceEntry AS S
WHERE (S.RunLogEntryID is not null) AND ([email protected])
AND EXISTS (SELECT ServiceEntryID
FROM ServiceEntryPart SEP
JOIN Part on SEP.PartID = Part.ID
WHERE ((@ActivePart = 0 AND Part.Active is not null)
OR (@ActivePart = 1 and Part.Active = 0))
AND (@ServiceTypes is null
OR CHARINDEX(','+cast(SEP.ServiceTypeIDs as varchar(255))+',',','[email protected]+',') > 0))
OR (NOT EXISTS (SELECT ServiceEntryID
FROM ServiceEntryPart SEP
JOIN Part on SEP.PartID = Part.ID))
服務條目包含的0 runlogentry ID一些記錄如果runlogentryid值服務條目表爲0,那麼該服務條目將不存在服務條目部分記錄。這就是爲什麼我把他們分成兩個,因爲你會發現從查詢例如存在和不存在。 exists語句負責所有具有服務條目部分的服務條目,對於這些條目,過濾器將適用。如果過濾器有值,則不需要不存在的塊,因爲過濾器servicetypeids和activepart僅用於具有服務入口部分的記錄。 換句話說,如果沒有params通過,第一個存在塊獲取具有服務部分的服務條目,而不存在獲取runlogentry id爲0或NOT null的服務條目。這很有效。問題是,當參數通過時,我需要排除沒有服務入口部分的服務入口,並且當它們出現時,我不會得到很好的結果。我希望我做了一個好工作解釋這個問題..請幫助
您的更新說明大多是合理的。但是你的數據與你陳述的規則相矛盾。您聲明如果ServiceEntry.RunLogEntry = 0,則不存在ServiceEntryPart記錄。然而ServiceEntry.ID = 1與該陳述相矛盾。此外,語句*「不存在獲取runlogentry id爲0或非空的服務條目」*對我沒有意義。我相信你的意思是說*「0或NULL」*。但是由於ServiceEntryID = 1,這不是真的。 – dbenham 2012-07-25 11:34:59