sql - 左连接列上的可选过滤器

标签 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      

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

出于某种原因,我现在似乎在放屁,但似乎无法理解 应该 做一些比较简单的事情

最佳答案

添加一个类似于下面的 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)

关于sql - 左连接列上的可选过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5332952/

相关文章:

sql - 在 WHERE 谓词解决方法中配置多个子查询

sql-server - 选择中左联接与子查询的奇怪问题

sql - SQL Server 是否缓存查询结果?

sql - 这是列出素数的好算法吗?

sql - 是否有任何专门用于聚合查询的数据库?

mysql - 即使记录不存在也返回行 一个表中的 2 个过滤器

sql - 尝试使用Prepare查询包含golang中的搜索

php - 将 ID 从 HTML 电子邮件传递到登陆页面,然后使用它来填充 SQL 查询

SQL 查询在 SQL Server 2012 中运行良好,但在 SQL Server 2008 R2 中无法执行

sql - 如何在现有表中创建代理键列?