左连接列上的可选过滤器

时间:2011-03-16 23:14:54

标签: sql tsql

我遇到了如何编写一个包含左连接上的可选过滤器的过程的问题。

我有两个表,问题和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      

这是有效的,它给了我所有的问题。但我想为客户位置代码添​​加一个可选参数,如果保留为null将返回所有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 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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)

答案 2 :(得分:2)

您的查询无法按预期运行的原因是,首先会检查2个ON条件,然后由于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 )