Reputation: 1177
Say we have two Users with ID = 1
and ID = 2
I know the ID
of the current User and I need to execute different select
statements depending on the ID
.
if ID = 1
select a from table1
else if ID = 2
select b from table2
else
select c from table3
Is there a way to put this logic into single SQL query?
Upvotes: 0
Views: 40
Reputation: 49270
You can use union
with appropriate where
conditions.
select a from table1 where id = 1
union all
select b from table2 where id = 2
union all
select c from table3 where id not in (1,2)
or if the tables can be join
ed
select
case when t1.id = 1 then t1.a
when t2.id = 2 then t2.b
else t3.c end
from table1 t1
join table2 t2 on t1.id = t2.id
join table3 t3 on t1.id = t3.id
Upvotes: 2