[英]Oracle - inner and left 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 ;
Output:输出:
a 1 a 1
bb 2 bb 2
a 1 a 1
bb 2 bb 2
d 4 (null) (null)
c 3 (null) (null)
Can we get the same above output from single scan of T1 and T2 ie from single query without UNION ALL etc?我们能否从 T1 和 T2 的单次扫描(即从没有 UNION ALL 等的单个查询中获得相同的输出)? Want to re-write the above Select query so that it scans the tables T1 and T2 only once and give the same result.
想要重写上面的 Select 查询,以便它只扫描表 T1 和 T2 一次并给出相同的结果。 See the LEFT join.
请参见 LEFT 连接。
The output cant be changed as we are passing it further in the application, duplicate data is required as per the requirement.当我们在应用程序中进一步传递输出时,输出无法更改,根据要求需要重复数据。
" Want to re-write the above Select query so that it scans the tables T1 and T2 only once"
“想要重写上面的 Select 查询,以便它只扫描表 T1 和 T2 一次”
You could use subquery factoring .您可以使用子查询分解。 The WITH clauses read each table once and the UNION-ed queries read from them:
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 ;
Here is a SQL Fiddle demo .这是一个 SQL Fiddle 演示。
You can avoid excess joins and unions by doubling the rows:您可以通过将行加倍来避免过多的连接和联合:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.