2013-07-08 65 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相同。否则,您需要指定正确的一组列。