I am trying to perform a SELECT query on two tables joined with a LEFT JOIN where there may not be a record in the joined table. Something like:
--SELECT row using AreaID
SELECT *
FROM Rate
LEFT JOIN Area
ON Rate.AreaID = Area.AreaID
WHERE ProductID = @ProductID
AND Area.PostcodeOutcode = @PostcodeOutcode
This works when @PostcodeOutcode exists in the Area table, but I still need to return the record in the left table if there is not a record in the right table.
I am fudging it currently by doing this, but I know there is a better solution:
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)
)
I know this is probably simple, but my SQL knowledge is limited. Please help.
Thanks
Alex
move the area check to the join
Update for the revised question in comments, Is this what you want?