Skip to content
Advertisement

Conditionally joining from multiple tables

Does SQL allow some form of conditional “table choosing” within the Join statement? ie. selecting a different table to join based on a predefined variable/condition.

define var = 1
select * 
from tbl
  join (case when &var=1 then tblA when &var=2 then tblB else tblC end) a on tbl.id = a.id

The error I get when attempting this method is ORA-00905: missing keyword.

Advertisement

Answer

No. Neither SQL nor Oracle allow this, unless you use dynamic SQL.

Assuming the tables have the same columns, you could write this logic as:

select * 
from tbl join
     (select a.* from tblA where &var = 1 union all
      select b.* from tblB where &var = 2 union all
      select c.* from tblC where &var not in (1, 2)
     ) abc
     on tbl.id = abc.id;
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement