SQL返回父行,即使没有子行 编辑我的问题*

SQL返回父行,即使没有子行 编辑我的问题*,sql,sql-server,select,ansi-nulls,Sql,Sql Server,Select,Ansi Nulls,我有一套桌子。当我在第二个表t2上进行筛选时,我仍然希望得到t1的所有行 下面是SQL脚本。我觉得自己在修修补补的时候离目标越来越近了,但我就是做不到 简言之,我需要t2的行(如果适用),但所有t1的行(在其他列中为空) 谢谢 create table t1 ( id int identity(1,1), parentName varchar(20) null ) create table t2 ( id int identity(1,1), t1id int not null, childNa

我有一套桌子。当我在第二个表t2上进行筛选时,我仍然希望得到t1的所有行

下面是SQL脚本。我觉得自己在修修补补的时候离目标越来越近了,但我就是做不到

简言之,我需要t2的行(如果适用),但所有t1的行(在其他列中为空)

谢谢

create table t1 ( id int identity(1,1), parentName varchar(20) null ) create table t2 ( id int identity(1,1), t1id int not null, childName varchar(20) null ) create table t3 ( id int identity(1,1), t2id int not null, gChildName varchar(20) null ) insert into t1 ( parentName ) values ( 'bob' ) insert into t1 ( parentName ) values ( 'john' ) insert into t2 ( childName, t1id ) values ( 'irving', 1 ) insert into t2 ( childName, t1id ) values ( 'parna', 1 ) insert into t2 ( childName, t1id ) values ( 'mike', 1 ) select t1.id, t1.parentName, t2.id, t2.childName from t1 left outer join t2 on t2.t1id = t1.id where t2.childName = 'mike' -- what i'd LIKE is: -- 1, bob, 3, mike -- 2, john, null, null drop table t3 drop table t2 drop table t1
正如其他人所提到的,您可以将t3筛选器移出整体WHERE子句并将其放入联接中,这会阻止它有效地将外部联接转换为伪内部联接,这是因为除了IS NULL之外,任何空值都无法匹配WHERE条件

这是对示例代码的一个非常简单的更改—只需更改到何处和


如果要联接两个或多个表,并且希望得到第一个表的结果,即使第二个或第三个表不匹配,等等,您只需要将联接更改为左联接。差不多

从表1 A中选择*


左连接表2 B在A.ID=B.RELATEDID上您可以简单地使用左连接:

Select t1.id,t1.name,t2.id id2,t2.name name2,t3.id id3,t3.name name3
From t1 left join
     t2 on t1.id=t2.t1id left join
     t3 on t3.t2id=t2.id
Where your condition here

听起来您可能正在使用左连接,但随后会根据where子句删除行。例如:

Select * from Table1 a
left join Table2 b
on a.ID = b.ID
where b.name like 'A%'
将从表1中删除表2中不匹配的所有行,即使您因b.name为null时不满足where条件而离开连接

要避免这种情况,请将条件放在联接中,如下所示:

Select * from Table1 a
left join Table2 b
on a.ID = b.ID and b.name like 'A&'
Select * from Table1 a
left join Table2 b
on a.ID = b.ID
where ISNULL(b.name, 'A') like 'A%'
或者在where子句中添加IsNull,如下所示:

Select * from Table1 a
left join Table2 b
on a.ID = b.ID and b.name like 'A&'
Select * from Table1 a
left join Table2 b
on a.ID = b.ID
where ISNULL(b.name, 'A') like 'A%'
编辑:现在您已经发布了您的查询,下面是一个具体的答案:只需更改到和的位置,它将返回您指定的结果

select
  t1.id,
  t1.parentName,
  t2.id,
  t2.childName
from #t1 t1 left outer join #t2 t2
  on t2.t1id = t1.id 
  and t2.childName = 'mike'

好的,听起来不刺耳,但我当然使用了外部连接,但当我过滤不存在的t3行时,我得到了零行。我需要t1信息和其他列的空值。好的,获得准确响应的一个好方法是公开一个您已经尝试过的示例代码块。无法判断您已经使用了外部联接。我已经编辑了我的答案,为您的t3过滤器添加了正确的位置。是的,我想我必须从查询t3.id=1中删除最终条件,并在客户端中过滤该条件;一切正常,直到我开始过滤最后一个表的值为止。我想这是意料之中的事,但我希望总是能得到table1的信息。只要把它放在加入中就行了——应该能得到你想要的。e、 g.从t1中选择*…在t2.ID=t3.t2ID和t3.ID=1上左键连接t3编辑我的初始问题,以使其更清晰。希望这有帮助。谢谢,谢谢@ChrisH!编辑我的答案以包含您的查询。graaaaarghhh!!!为什么我以前没看到过无数次的网络搜索???谢谢显然,忽略这里的表3,因为它没有被使用;尽量让事情简单些。谢谢