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

Ale*_*lex 3 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
Run Code Online (Sandbox Code Playgroud)

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

我这样做是在捏造它,但我知道有一个更好的解决方案:

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)
)
Run Code Online (Sandbox Code Playgroud)

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

谢谢

亚历克斯

Bob*_*ale 5

将区域检查移动到连接

SELECT * FROM Rate
LEFT JOIN Area 
  ON Rate.AreaID = Area.AreaID and Area.PostcodeOutcode = @PostcodeOutcode
WHERE ProductID = @ProductID 
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)