SQL Server - 选择左连接 NULL 记录 WHERE 条件

标签 sql sql-server join

我正在尝试对使用 LEFT JOIN 连接的两个表执行 SELECT 查询,其中连接的表中可能没有记录。比如:

--SELECT row using AreaID
SELECT *
FROM Rate
LEFT JOIN Area
ON Rate.AreaID = Area.AreaID
WHERE ProductID = @ProductID
AND Area.PostcodeOutcode = @PostcodeOutcode

这在Area表中存在@PostcodeOutcode时有效,但是如果右表中没有记录,我仍然需要返回左表中的记录。

我目前正在这样做,但我知道有更好的解决方案:

DECLARE @AreaID int
SELECT @AreaID = AreaID
FROM Area WHERE PostcodeOutcode = @PostcodeOutcode 

--SELECT row using AreaID
SELECT *
FROM Rate
WHERE ProductID = @ProductID
AND
(
    AreaID = @AreaID
    OR (@AreaID IS NULL AND AreaID IS NULL)
)

我知道这可能很简单,但我的 SQL 知识有限。请帮忙。

谢谢

亚历克斯

最佳答案

将区域检查移动到连接处

SELECT * FROM Rate
LEFT JOIN Area 
  ON Rate.AreaID = Area.AreaID and Area.PostcodeOutcode = @PostcodeOutcode
WHERE ProductID = @ProductID 

更新评论中修改后的问题,这是你想要的吗?

SELECT Rate.RatePercent FROM Rate
INNER JOIN Area 
  ON Rate.AreaID = Area.AreaID and Area.PostcodeOutcode = @PostcodeOutcode
WHERE 
  ProductID = @ProductID
UNION ALL
SELECT Rate.RatePercent FROM Rate 
where
  ProductID = @ProductID 
and 
  AreaId is null 
and 
 not exists(select PostCodeOutCode From Area where PostCodeOutCode=@PostCodeOutcode)

关于SQL Server - 选择左连接 NULL 记录 WHERE 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7075934/

相关文章:

sql - 如何获取所有自动生成的外键名称?

sql - LEFT 对于相同的值返回不同的结果

mysql - DELETE 语句中 INNER 和 LEFT join 有什么区别?

java - 如何在 Java 中使用带问号的 strftime 函数

mysql - 1条sql语句中的多重计数

sql - 学生校内查询

c# - 将 LINQ to EF 查询加速到最大

php - 连接没有公共(public) ID 的三个表 #MySQL

mysql - 将两个mysql表合并为一行

php - 用于搜索字符串中每个空格后的每个值的 SQL 查询