postgresql - Postgres Select from a Table Based On Query Result -


i have 2 tables identical columns, in identical order. have desire join across 1 of 2 tables, depending on subquery condition. example, assume have following schema:

create table b (     bid serial primary key,     cid int not null );  create table a1 (     aid serial primary key,     bid int not null references b );  create table a2 (     aid serial primary key,     bid int not null references b ); 

i query, performs join across either a1 or a2 based on condition. like:

with z (   select cid, somecondition sometable ) select * case z.somecondition a1 else a2 end join b using (bid) cid = (select cid z); 

however, above doesn't work. there way conditionally join across a1 or a2, depending on boolean condition stored in table z?

if conditions exclusive (i expect are): both queries , union all them, smart union construct:

with z (   select cid         , (cid %3) some_condition -- fake ...           b   ) select *   a1   join b using (bid)  exists( select * z         some_condition = 1 , cid = b.cid ) union select *   a2   join b using (bid)  exists( select * z         some_condition = 2 , cid = b.cid )         ; 

a different syntax same:

with z (   select cid         , (cid %3) some_condition           b ) select *   a1   join b on a1.bid = b.bid         , exists( select * z         some_condition = 1 , cid = b.cid ) union select *   a2   join b on a2.bid = b.bid         , exists( select * z         some_condition = 2 , cid = b.cid )         ; 

Comments