2013-07-08 67 views
0

這裏是我的情況:查詢兩個表的條​​件,從第三個表

table a 
    table b 
    table c (type int) 

if c.type = 1 select all rows in table a 
if c.type = 2 select all rows in table b 

目前我的解決辦法是找到所有行的3個表和處理結果得到的值,但它是非常糟糕的。

回答

1

您不指定表格之間的關係。表達式c.type引用一行,而不是整個表。所以,讓我假設c.type = 1的意思是「存在一行,其中c.type = 1」。

的解決這個問題的是然後有條件union all

select a.* 
from tablea a 
where exists (select 1 from tablec c where c.type = 1) 
union all 
select b.* 
from tableb b 
where exists (select 1 from tablec c where c.type = 2) 

這假定該列是ab相同。否則,您需要指定正確的一組列。