2011-03-16 24 views
3

我遇到的問題正在圍繞如何編寫包含左連接上的可選過濾器的過程。左連接列上的可選過濾器

我有兩個表格,問題和Customer_Location。並非所有問題都與客戶所在地相關聯。所以我很好,以此爲出發點:

SELECT 
    I.Issue_Number, 
    C.Customer_Location_Code 

FROM Issues I 
LEFT JOIN Customer_Location C 
    ON C.Customer_Location_Key = I.Customer_Location_Key 


Issue_Number | Customer_Location_Code 
1   | Chicago 
2   | NULL 
3   | Chicago 
4   | New York  

而這個工程,它給了我所有的問題。但是我想爲客戶位置代碼添​​加一個可選參數,如果留空即會返回所有4個問題,但如果設置爲1表示芝加哥,則只會返回問題1和3。

我已經試過這

DECLARE @customer_location_key INT 
SET @customer_location_key = 1 

SELECT 
    I.Issue_Number, 
    C.Customer_Location_Code 

FROM Issues I 
LEFT JOIN Customer_Location C 
    ON C.Customer_Location_Key = I.Customer_Location_Key 
AND C.Customer_Location_Key = @customer_location_key 

但我得到下面的結果

Issue_Number | Customer_Location_Code 
1   | Chicago 
2   | NULL 
3   | Chicago 
4   | NULL 

出於某種原因,我似乎現在是具有腦屁,只是似乎無法得到我的腦袋圍繞什麼應該是一件相當簡單的事

回答

3

添加有類似以下條款應該這樣做。

DECLARE @customer_location_key INT 
SET @customer_location_key = 1 

SELECT 
    I.Issue_Number, 
    C.Customer_Location_Code 

FROM Issues I 
LEFT JOIN Customer_Location C 
    ON C.Customer_Location_Key = I.Customer_Location_Key 
where (@customer_location_key is null or C.Customer_Location_Key = @customer_location_key) 
2

您的查詢不能按預期工作的原因是首先是2 0123檢查條件,然後由於LEFT JOIN,還添加了表Issue的所有未匹配的行(表Customer_Location_Code的列中爲NULL)。

DECLARE @customer_location_key INT 
SET @customer_location_key = 1 

SELECT 
    I.Issue_Number, 
    C.Customer_Location_Code 

FROM Issues I 
LEFT JOIN Customer_Location C 
    ON C.Customer_Location_Key = I.Customer_Location_Key 
WHERE (@customer_location_key IS NULL) 
    OR (C.Customer_Location_Key = @customer_location_key) 
3

使用WHERE子句,而不是

DECLARE @customer_location_key INT 
SET @customer_location_key = 1 

SELECT 
    I.Issue_Number, 
    C.Customer_Location_Code 

FROM Issues I 
LEFT JOIN Customer_Location C 
    ON C.Customer_Location_Key = I.Customer_Location_Key 
WHERE 
(@customer_location_key is null OR C.Customer_Location_Key = @customer_location_key)