sql server - SQL Conditional Join With Same Alias -
i have join clause in query this.
select table1.number table1 join table2 table on table2.table1_id = table1.id join table3 table on table3.table1_id = table1.id join othertable on table.id = othertable.table_id
i want conditionally join 1 of tables 2 or 3 depending on table.number , retain alias name other tables still join them.
select t1.*, ot.* table1 t1 inner join ( select 1 number, t.col, t.table1_id, t.table_id table2 union select 2 number, t.col, t.table1_id, t.table_id table3 ) t2 on t2.number = t1.number , t2.table1_id = t1.id inner join othertable ot on ot.table_id = t2.table_id
or (could less efficient)
select t1.*, ot.* table1 t1 left outer join table2 tmp1 on tmp1.table1_id = t1.id , t1.number = 1 left outer join table3 tmp2 on tmp2.table1_id = t1.id , t1.number = 2 cross apply (select isnull(tmp1.table_id, tmp2.table_id) table_id) t2 inner join othertable ot on ot.table_id = t2.table_id
Comments
Post a Comment