2
  • 質問の編集 *

私はテーブルのセットを持っています。2 番目のテーブル t2 をフィルター処理するとき、t1 のすべての行を取得したいと考えています。

SQLスクリプトは以下です。いじりながら近づいている気がするのですが、なかなか実現できません。

つまり、該当する場合は t2 の行が必要ですが、t1 の行はすべて、他の列に null があります。

ありがとう。

テーブル t1 を作成します (id int identity(1,1), parentName varchar(20) null )
テーブル t2 を作成します (id int identity(1,1), t1id int not null, childName varchar(20) null )
テーブル t3 を作成します ( id int identity(1,1), t2id int not null, gChildName varchar(20) null )

t1 (parentName) 値 ('bob') に挿入
t1 (parentName) 値 ('john') に挿入します。

t2 ( childName, t1id ) 値 ( 'irving', 1 ) に挿入
t2 ( childName, t1id ) 値 ( 'parna', 1 ) に挿入
t2 ( childName, t1id ) 値 ( 'mike', 1 ) に挿入

選択する
      t1.id、
      t1.parentName、
      t2.id、
      t2.childName
t1 左外部結合 t2 から
      t2.t1id = t1.id で
どこで t2.childName = 'マイク'

-- 私が望むのは:
-- 1、ボブ、3、マイク
-- 2、ジョン、ヌル、ヌル

ドロップテーブル t3
ドロップテーブル t2
ドロップテーブル t1
4

4 に答える 4

4

他の人が述べたように、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
于 2015-04-23T19:27:34.817 に答える
0

2 つ以上のテーブルを結合していて、2 番目 (または 3 番目など) からの一致がなくても最初の結果が必要な場合は、結合を左結合に変更するだけです。何かのようなもの

SELECT * FROM TABLE1 A

A.ID=B.RELATEDID の LEFT JOIN TABLE2 B

于 2015-04-23T19:28:23.460 に答える
0

左結合を使用するだけです。

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
于 2015-04-23T19:32:44.390 に答える