首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SQL Joins : in,out,shake all

SQL Joins : in,out,shake all
EN

Stack Overflow用户
提问于 2010-11-05 17:49:42
回答 4查看 175关注 0票数 1

我正在执行下面的sql以返回一个数据,其中存在tables1 & 2中的道布和地址的匹配。

代码语言:javascript
复制
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就可以执行所需的操作,但事实并非如此。

谢谢!

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2010-11-05 17:52:58

如果连接中没有匹配项,则第二个表中的字段为NULL,因此您必须检查table2中是否有NULL值。假设table2中的道布不为空,这应该可以解决您的问题:

代码语言:javascript
复制
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
票数 2
EN

Stack Overflow用户

发布于 2010-11-05 17:52:33

在这种情况下,thre不是一个连接,你应该使用NOT EXISTS函数。

票数 2
EN

Stack Overflow用户

发布于 2010-11-06 04:23:45

在我看来,LEFT JOIN要干净得多,如果LEFT JOIN和NOT EXISTS的性能没有太大差异,你应该这样做。@JNK说"EXISTS和NOT EXISTS通常比joins或其他像IN这样的运算符更快,因为它们短路--当它们第一次命中时,它们会转移到下一个条目“,但我的理解是NOT EXISTS和NOT IN通常是昂贵的,因为sql server必须检查查找表中的所有记录,以确保条目实际上不存在,所以我不知道短路是如何工作的

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4104830

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档