左边加入自我标准

时间:2013-02-20 20:34:39

标签: sql sql-server left-join

设置

create table #history (
adddttm date,
number int
)
insert into #history values ('2013-01-01 08:56:00.000',1);
insert into #history values ('2013-01-01 08:56:00.000',2);
insert into #history values ('2013-02-13 08:56:00.000',2);
insert into #history values ('2013-02-13 08:56:00.000',3);

查询

select *
from #history new
left join #history old
  on new.number = old.number
where new.adddttm = '2013-02-13 08:56:00.000'
and   old.adddttm = '2013-01-01 08:56:00.000'

我希望以下查询返回:

----------|-|----------|-
2013-02-13|2|2013-01-01|2
2013-02-13|3|null      |null

但我从来没有得到第二排。为什么这个左连接会跳过丢失的行?

2 个答案:

答案 0 :(得分:1)

非常简单,因为在where子句中引用了old.adddttm。我写了一篇文章Fun with Outer Joins,其中详细说明了原因。同样非常简单,因为ON子句仅用于两个表之间的连接,而WHERE子句仅用于对结果集的限制。但是很容易混淆两者。

此查询将有效。

select *
from #history new
left join #history old
  on new.number = old.number 
  and old.adddttm = '2013-01-01 08:56:00.000'
WHERE new.adddttm = '2013-02-13 08:56:00.000'

答案 1 :(得分:1)

您的where子句不包括该行。

select old.*
from history new
left join history old
  on new.number = old.number and old.adddttm = '2013-01-01 08:56:00.000' 
where new.adddttm = '2013-02-13 08:56:00.000' 

现在,当它没有获得连接行时,您会按预期获得空值。