私は次のようにしたいと思います:
Select * from
table1 a
inner join table2 b
on
a.id = b.id
if (some condition is met) // Now it gets interesting!
begin
and a.name = b.name
end
明らかに、これは機能しません。
これをどのように達成するのが最善でしょうか?
ありがとうスタッカーズ!
私は次のようにしたいと思います:
Select * from
table1 a
inner join table2 b
on
a.id = b.id
if (some condition is met) // Now it gets interesting!
begin
and a.name = b.name
end
明らかに、これは機能しません。
これをどのように達成するのが最善でしょうか?
ありがとうスタッカーズ!
条件を WHERE 節に入れることができないのはなぜですか?
通常、条件付き結合は次のようになります。
Select *
from table1 a
inner join table2 b
on (a.conditional_field = 1 and a.id = b.id)
or (a.conditional_field = 2 and a.id2 = b.id2)
ここで注意すべき重要なことは、結合自体ではなく、結合条件をオプションにすることです。結合自体を条件付きにする場合は、それが外部結合の目的です。
Select *
from table1 a
left outer join table2 b
on a.id = b.id
最初のクエリは、いずれかの条件がtrueの場合に一致するすべての行を返します。2番目のクエリは、条件がtrueであるすべての行table1
とそれらの行のみを無条件に返します。table2
私は次のようなものを使用します:
SELECT * FROM table1 a
JOIN table2 b ON (a.id = b.id)
WHERE NOT ( == your condition here == ) OR a.name = b.name
本当に結合条件に入れたい場合は、次のようにすることができます。
SELECT * FROM table1 a
JOIN table2 b ON (a.id = b.id AND (NOT ( == your condition here == ) OR a.name = b.name))
しかし、最初の形式の方が明確だと思います。
編集:@James Curtisがコメントで指摘したように:
WHERE 句に条件を入れるオプションは、INNER JOIN に対してのみ有効であることに注意してください。外部結合では、行を削除できます。