我正在尝试对与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)

10-08 11:08