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

时间:2011-08-16 09:11:20

标签: 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

这在@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)
)

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

由于

亚历

2 个答案:

答案 0 :(得分:5)

将区域检查移至联接

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)

答案 1 :(得分:4)

这两者之间的左联接有所不同:

Select *
From Table1 t1
Left Outer Join Table2 t2 On t2.id = t1.id
Where t2.somevalue = @SomeParameter

Select *
From dbo.Table1 t1
Left Outer Join dbo.Table2 t2 On t2.id = t1.id And t2.somevalue = @SomeParameter

后者将过滤Table2,而前者将过滤Table1和Table2之间的连接。所以,这意味着第一个查询将连接id上的两个表中的所有行,然后过滤somevalue与参数不匹配的那些,即这通常也会过滤掉somevalue为null的那些,因为没有行。

第二个查询将table1与table2连接在id上,但table2首先在匹配参数上进行过滤,因此也会返回不匹配的行,因此不会过滤掉。

旁注:您应始终在查询中提供表格的架构(出于性能原因)。

相关问题