2013-06-12 152 views
0

在我的數據庫我有保存所有文件怪異的行爲

這個表有幾個依賴表(讓我們爲它們命名:FilesDep1,FilesDep2,FilesDep3,FilesDep4,FilesDep5)

文件表擁有超過20000條記錄,我需要篩選出五個依賴項中沒有任何一個使用的文件。

所以我用工會所有的fileid的從FilesDep1

select Id from [Files] where Id not in 
(
    select FileId from [FilesDep1] 
    union 
    select FileId from [FilesDep2] 
    union 
    select FileId from [FilesDep3] 
    union 
    select FileId from [FilesDep4] 
    union 
    select FileId from [FilesDep5] 
) 

所有工會給予的量是1997年。因此,我希望得到該查詢18000+的記錄,但是。 ..它返回0?

我想知道是什麼原因導致此行爲?

如果我改變not inin,它確實表明了1997年的記錄由unionquery給...

PS。請不要回應表的命名,或者我使用union來進行查詢而不是內部連接或其他事情。這個問題是關於爲什麼聯合查詢不能按預期工作。

+5

'NOT IN ...(NULL)'總是不返回行,不論什麼'NOT NULL '值也可能被返回。 –

+0

-1由於*「請不要回應...或別的東西」*評論;你已經有效地排除了回答你的問題「爲什麼會發生這種情況」的任何迴應。正如馬丁所觀察到的,這幾乎肯定是由於包含null的'not in'子查詢所導致的,這就是爲什麼這種查詢最好使用'not exists'或'left join ... where null'條件處理的原因。 –

+0

@ Mary:我看不到你的觀點。因爲我知道很多人會開始抱怨這不是正確的方式或最佳做法。我意識到這一點,因此我加入了這個問題,我知道這一點,而我只是試圖找出是什麼原因導致了這種行爲,並且對於人們告訴我這是不好的做法或糟糕的編程不感興趣。 –

回答

1

你可能在某處有FieleID的NULL值?如果您的子查詢的結果中存在單個NULL值,NOT IN將無法按預期工作。

您可以處理空值

select Id from [Files] where Id not in 
(
    select FileId from [FilesDep1] where FileID is NOT NULL 
    union 
    select FileId from [FilesDep2] where FileID is NOT NULL 
    union 
    select FileId from [FilesDep3] where FileID is NOT NULL 
    union 
    select FileId from [FilesDep4] where FileID is NOT NULL 
    union 
    select FileId from [FilesDep5] where FileID is NOT NULL 
) 

或更換不符合NOT EXISTS

select f.Id from [Files] f where NOT EXISTS 
(SELECT * FROM 
(
    select FileId from [FilesDep1] 
    union 
    select FileId from [FilesDep2] 
    union 
    select FileId from [FilesDep3] 
    union 
    select FileId from [FilesDep4] 
    union 
    select FileId from [FilesDep5] 
) x 
WHERE x.FileID = f.ID)