怎么减去工作

时间:2015-11-30 19:03:07

标签: sql oracle join

我有2张桌子

create table table1 (tb1 number);
insert into table1 values (13);
insert into table1 values (14);
insert into table1 values (15);
insert into table1 values (16);
create table table2(tb2 number);
insert into table2 values (13);
insert into table2 values (14);
insert into table2 values (25);
insert into table2 values (26);

我想在左列中输出内连接值,在右列中输出右表中的右边值。所以它应该是

13 25
14 26

我尝试使用减号

select  table1.tb1, table2.tb2  from table1 right  join table2 on table1.tb1= table2.tb2 
minus 
select  null, table2.tb2 from table1 inner join table2 on table1.tb1=table2.tb2
;

但我得到了

13 13
14 14
   25
   26

我该怎么办?单独两个选项工作正常,我只想做第一个选择结果减去第二个选择结果。

1 个答案:

答案 0 :(得分:3)

为什么

13 25
14 26

而不是

13 26
14 25

如果你只是要求第一列是一个行列表,按数字顺序排列在table1和table2中,而第2列是table2中存在但不是table1的行,那么你正在考虑带来返回两个可能具有不同长度的不相关列表。在这种情况下,任何给定行中的值之间的相关性是它们在各自数据集中的排名

所以 - 可以这样做:

with t1 as ( 
          select 13 a from dual
union all select 14 a from dual
union all select 15 a from dual
union all select 16 a from dual)
, t2 as (
          select 13 a from dual
union all select 14 a from dual
union all select 25 a from dual
union all select 26 a from dual)
select sub1.a  t1_a
      ,sub2.a  t2_a
from      
(-- subquery to get common values and their rankings
 select t1.a
      ,rank() over (order by t1.a) rnk
from t1 join t2 on t1.a = t2.a) sub1
full outer join 
(--subquery to get the values only in t2 and their rankings
 select t2.a
      ,rank() over (order by t2.a) rnk
from t1 right outer join t2 on t2.a = t1.a
where t1.a is null) sub2
-- join on the ranking. This is needed to avoid a cartesien product.
using (rnk)

t1_A                                   t2_a                                    
13                                     25                                     
14                                     26