内部连接一个查询中的两个SELECT语句并显示来自BOTH表的结果

时间:2015-12-28 15:02:32

标签: sql oracle

我希望使用2个SELECT语句和来自不同查询的INNER JOIN但是也希望从同一查询中的不同表中显示两个不同的结果。像这样......

  SELECT column1 FROM earth e1 that is null
                     +
  SELECT chair5 FROM space s1 that is not null

  INNER JOIN space s1 ON e1.car = s1.truck

  ORDER BY e1.column,s1.chair5

如何在使用INNER JOIN时显示两个不同查询的结果?

1 个答案:

答案 0 :(得分:0)

假设表格T1包含值'A','B','C',而表格T2包含值'A','B','D'

您可以查询

select 'T1' as source, col from t1
union all
select 'T2' as source, col from t2
union all
select 'join T1,T2' as source, t1.col from t1 inner join t2
on t1.col= t2.col
order by 1,2
;

获得

SOURCE     COL  
---------- -----
T1         A    
T1         B    
T1         C     
T2         A      
T2         B    
T2         D   
join T1,T2 A   
join T1,T2 B

第一列标识源:单个查询或连接

或者,我更喜欢你可以使用FULL OUTER JOIN获得相同的信息(压缩更多)

with fj as (
select t1.col t1_col, t2.col t2_col 
from t1 full outer join t2
on t1.col= t2.col
)
select 
case when t1_col is not null and t2_col is not null then 'both'
when  t1_col is not null   then 'T1 only'
when  t2_col is not null then 'T2 only' end as source,
nvl(t1_col, t2_col) col
from fj
order by 1,2

SOURCE  COL  
------- ----------
T1 only C        
T2 only D       
both    A      
both    B