2016-07-20 45 views
0

假設我們有兩個用戶用ID = 1ID = 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查詢的方式?

+0

ID在表1,表2,表3或可變的,並且列有任何與名字ID這些表列? –

回答

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 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 
+0

根據我的理解,如果每次僅滿足一個條件,則此方法會導致冗餘計算。 – serhii

+0

@Sloth這個計算需要幾毫秒。如果條件始終爲假,則CBO非常聰明,不會獲取數據(如果id = 2,則表示1 = 2) –

+0

@EvgeniyK。想象一下,如果對條件的評估足夠昂貴。 我的例子非常簡化 – serhii

相關問題