假设我们有两位用户ID = 1
和ID = 2
我知道当前用户的ID
,我需要执行不同的select
语句,具体取决于ID
。
if ID = 1
select a from table1
else if ID = 2
select b from table2
else
select c from table3
有没有办法将此逻辑放入单个 SQL 查询中?
答案 0 :(得分:2)
您可以union
使用适当的where
条件。
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)
或表格是否可以join
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