2016-07-11 9 views
1

いくつかのレコードセットがありますが、2つのテーブルのいずれかにtheeir IDを持つレコードをこのセットから選択する必要があります。SQLサーバーで条件付きで結合を適用する

は、私は今、私は自分のID表2または表3のいずれか

私が適用しようとしていた

またはオペレータを持つ表1 からレコードだけを選択する必要が

Id Name 
---------- 
1 Name1 
2 Name2 

が含まれているTABLE1があると内部のような結合:

select * 
from table1 
inner join table2 on table2.id = table1.id or 
inner join table3 on table3.id = table1.id. 

可能ですか?これにアプローチする最善の方法は何ですか?実際に私も使用できません

if exist(select 1 from table2 where id=table1.id) then select from table1 

誰かが私を助けることができますか?その後、

+0

をあなたを介して半分の方法です:選択* table1の内部からtable2.id = table1.idにtable2のに参加 インナーは= table3.id上の表3に参加しますtable1.id。 – TheGameiswar

+0

ここの結合について読む:http://stackoverflow.com/questions/38549/difference-between-inner-and-outer-joins/27458534 – TheGameiswar

答えて

1

私はexistsを使用するように傾斜させることになります。

select t1.* 
from table1 t1 
where exists (select 1 from table2 t2 where t2.id = t1.id) or 
     exists (select 1 from table3 t3 where t3.id = t1.id) ; 

exists(またはin)を結合に使用する利点は、重複する行を伴います。 table2またはtable3が与えられたidに対して複数の行を持つ場合、joinを使用するバージョンは結果セットに複数の行を生成します。

2

使用left joinと合流の少なくとも一つは、私が最も効率的な方法は、表2と表3にUNIONを使用して、それに参加することだと思う関係

select t1.* 
from table1 t1 
left join table2 t2 on t2.id = t1.id 
left join table3 t3 on t3.id = t1.id 
where t2.id is not null 
    or t3.is is not null 
1

発見したかどうかを確認:

SELECT t1.* 
FROM table1 t1 
INNER JOIN(SELECT id FROM Table2 
      UNION 
      SELECT id FROM Table3) s 
ON(t.id = s.id) 
1

また、あなたが同様にSQLの下に使用することができます。

SELECT * 
FROM dbo.Table1 
WHERE id Table1.IN (SELECT table2.id 
       FROM dbo.table2) 
     OR Table1.id IN (SELECT table3.id 
        FROM  Table3)