我试图在与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知识有限.请帮忙.
谢谢
亚历克斯