假設我們有兩個用戶用ID = 1
和ID = 2
執行不同的語句在一個查詢的條件
我知道當前用戶的ID
,我需要執行取決於ID
不同select
聲明。
if ID = 1
select a from table1
else if ID = 2
select b from table2
else
select c from table3
有沒有把這個邏輯爲單SQL查詢的方式?
假設我們有兩個用戶用ID = 1
和ID = 2
執行不同的語句在一個查詢的條件
我知道當前用戶的ID
,我需要執行取決於ID
不同select
聲明。
if ID = 1
select a from table1
else if ID = 2
select b from table2
else
select c from table3
有沒有把這個邏輯爲單SQL查詢的方式?
您可以使用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
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
ID在表1,表2,表3或可變的,並且列有任何與名字ID這些表列? –