看來,當有內部CTE子查詢NULL值(如果我更換刀片(1,NULL NULL)與假設(1查詢沒有返回值,0),您的查詢將工作)。如果你想獲得不屬於任何其他類別的父母甚至NULL值的類別,你可以做這樣的:
DECLARE @Category TABLE (CategoryID INT, Parent_CategoryID INT)
INSERT @Category VALUES
(1, NULL),
(2, 1),
(3, 1),
(4, 2)
;WITH pricedCategories AS
(
SELECT * FROM @Category y WHERE NOT EXISTS
(SELECT Parent_CategoryID FROM @Category x
WHERE x.Parent_CategoryID = y.CategoryID)
)
SELECT * FROM pricedCategories
有趣的是,看到下面的方法效果相同,所描述的方法你的問題:
;WITH pricedCategories AS
(
SELECT * FROM @Category y
WHERE y.CategoryID <> ALL(SELECT DISTINCT Parent_CategoryID FROM @Category)
)
SELECT * FROM pricedCategories
你可以改變你的查詢使用ISNULL函數替換NULL與從不用作類別ID一些數值,像這樣:
;WITH pricedCategories AS
(
SELECT * FROM @Category WHERE CategoryID NOT IN
(SELECT ISNULL(Parent_CategoryID, -1) FROM @Category)
)
SELECT * FROM pricedCategories
但是,那麼意味着「無」的NULL值將更改爲-1的實際值,這是不正確的,你不應該使用它。
我知道這個方法,但我經常使用這種類型的查詢,而且這種方法不太直觀和快速。它吃了一點你的大腦,但「不在」沒有。 – teenup 2012-07-07 10:13:08
@puretechy - 如果你想繼續使用NOT NOT,只需從你的子查詢中排除NULL值。即。 'CategoryID不在(從Product.Category中選擇Parent_CategoryID WHERE Parent_CategoryID不爲NULL)' – 2012-07-07 10:43:55