gpt4 book ai didi

SQL即使没有子行也返回父行

转载 作者:行者123 更新时间:2023-12-02 17:33:34 26 4
gpt4 key购买 nike

  • 编辑我的问题*

我有一组表格。当我在第二个表 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.childNamefrom t1 left outer join t2      on t2.t1id = t1.idwhere t2.childName = 'mike'-- what i'd LIKE is:-- 1, bob, 3, mike-- 2, john, null, nulldrop table t3drop table t2drop table t1

最佳答案

正如其他人所提到的,您可以将 t3 过滤器移出整个 WHERE 子句并将其放入 JOIN 中,这可以防止它有效地转换您的外部连接进入一个伪内部连接(发生这种情况是因为没有一个 NULL 值可以匹配 WHERE 条件,除了 IS NULL)

这是对示例代码的非常直接的更改 - 只需将 WHERE 更改为 AND

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 and t2.childName = 'mike'

drop table t3
drop table t2
drop table t1

关于SQL即使没有子行也返回父行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29832549/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com