来自两个以上表的列数,不使用完全外连接

时间:2015-08-05 03:36:24

标签: oracle sybase oracle-apex

我有两个名为tb1和tb2的表,如下所示,

tb1
mtdata mtproject mtteam mtdetails 
a apple fruits 'fruits family'
a orange fruits 'fruits family'
b tomatto veg 'vegtable family'
b beatroot root 'vegtable family' 

tb2 
mtproject rrequester rdate
apple x xxxxx 
orange y xxxxx 
apple xx xxxxx
apple xz xxxxx 

我想得到以下细节:mtdata,mtproject,mtteam,count(project)其中(x,y,z)中的rrequester为yes_count和count(project)其中rrequester不在(x,y,z)No_count

请帮助我使用完全外部联接进行查询。提前感谢。

1 个答案:

答案 0 :(得分:0)

我不确定为什么有人会在左连接时使用全外连接:

select tb1.mtdata
     , tb1.mtproject
     , tb1.mtteam
     , count(case when rrequester in ('x','y','z') then 1 else null end) yes_count
     , count(case when rrequester not in ('x','y','z') then 1 else null end) no_count
  from tb1
  left join tb2
    on tb1.mtproject = tb2.mtproject
 group by tb1.mtdata
     , tb1.mtproject
     , tb1.mtteam;

通过使用标量子查询,您甚至可以在没有任何外部连接的情况下使用:

select tb1.mtdata
     , tb1.mtproject
     , tb1.mtteam
     , (select count(*) from tb2 where tb2.mtproject = tb1.mtproject and rrequester in ('x','y','z')) yes_count
     , (select count(*) from tb2 where tb2.mtproject = tb1.mtproject and rrequester not in ('x','y','z')) no_count
  from tb1;

标量子查询应该谨慎,因为它们的性能可能低于等效的连接操作。