Oracle - 内部和左侧连接

时间:2018-02-21 08:34:26

标签: sql oracle join outer-join

create table t1 (v varchar2(500), n number);
Insert into T1 (V,N) values ('a',1);
Insert into T1 (V,N) values ('bb',2);
Insert into T1 (V,N) values ('c',3);
Insert into T1 (V,N) values ('d',4);

create table t2 (v varchar2(500), n number);
Insert into T2 (V,N) values ('a',1);
Insert into T2 (V,N) values ('bb',2);

select * from t1 join t2 on t1.v = t2.v 
union all
select * from t1 LEFT join t2 on t1.v = t2.v ;

输出:

    a     1     a         1
    bb    2     bb        2
    a     1     a         1
    bb    2     bb        2
    d     4     (null)  (null)
    c     3     (null)  (null)

我们可以从T1和T2的单次扫描中获得相同的上述输出,即来自没有UNION ALL等的单一查询吗?想要重新编写上面的Select查询,以便它只扫描表T1和T2一次,并给出相同的结果。请参阅LEFT join。

输出无法更改,因为我们在应用程序中进一步传递输出,根据要求需要重复数据。

2 个答案:

答案 0 :(得分:1)

  

“想要重新编写上面的Select查询,以便它只扫描表T1和T2”

您可以使用子查询因子分解。 WITH子句读取每个表一次,UNION-ed查询从它们读取:

with cte1 as ( select * from t1 )
   , cte2 as ( select * from t2 ) 
select * from cte1 join cte2 on cte1.v = cte2.v 
union all
select * from cte1 LEFT join cte2 on cte1.v = cte2.v ;

这是a SQL Fiddle demo

答案 1 :(得分:0)

你可以通过加倍行来避免多余的连接和联合:

select t1.*,t2.* from t1
  left join t2 on t1.v=t2.v
  cross join (select 1 as dbl from dual 
            union select 2 as dbl from dual) dbl
where dbl=1 or t2.v is not null