我正在尝试对使用 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/