我正在执行下面的sql以返回一个数据,其中存在tables1 & 2中的道布和地址的匹配。
select table1.dob
, table1.address
, sum(case when person_status in ('A','B','C') then 1 else 0 end) as 'ABC_count'
, sum(case when person_status in ('D','E') then 1 else 0 end) as 'DE_Count'
, sum(case when person_status in ('F','G') then 1 else 0 end) as 'FG_Count'
from table1
inner join table2
on (table1.dob = table2.dob and table1.address = table2.address)
where table1.dob > @myDate
group by table1.dob, table1.address
order by table1.dob, table1.address然而,我现在想在table2中没有匹配项而只返回这些数据时从table1返回数据,我以为只需将inner更改为left outer就可以执行所需的操作,但事实并非如此。
谢谢!
发布于 2010-11-05 17:52:58
如果连接中没有匹配项,则第二个表中的字段为NULL,因此您必须检查table2中是否有NULL值。假设table2中的道布不为空,这应该可以解决您的问题:
select table1.dob
, table1.address
, sum(case when person_status in ('A','B','C') then 1 else 0 end) as 'ABC_count'
, sum(case when person_status in ('D','E') then 1 else 0 end) as 'DE_Count'
, sum(case when person_status in ('F','G') then 1 else 0 end) as 'FG_Count'
from table1
left outer join table2
on (table1.dob = table2.dob and table1.address = table2.address)
where table1.dob > @myDate and table2.dob is null
group by table1.dob, table1.address
order by table1.dob, table1.address发布于 2010-11-05 17:52:33
在这种情况下,thre不是一个连接,你应该使用NOT EXISTS函数。
发布于 2010-11-06 04:23:45
在我看来,LEFT JOIN要干净得多,如果LEFT JOIN和NOT EXISTS的性能没有太大差异,你应该这样做。@JNK说"EXISTS和NOT EXISTS通常比joins或其他像IN这样的运算符更快,因为它们短路--当它们第一次命中时,它们会转移到下一个条目“,但我的理解是NOT EXISTS和NOT IN通常是昂贵的,因为sql server必须检查查找表中的所有记录,以确保条目实际上不存在,所以我不知道短路是如何工作的
https://stackoverflow.com/questions/4104830
复制相似问题