select A.code,nvl((select sum(C.a) from C where C.aid = A.aid and C.bid = B.bid ),0) from A,B where A.code = B.code,C表数据可能为空,目前效率很慢,能否优化SQL

解决方案 »

  1.   

    快不快跟数据特征有关。实在不行就上索引把
    select a.a_code,
           nvl(sum(c.a), 0)
      from (
    select A.code a_code,
           B.code b_code
      from A, B
     where A.code = B.code
     ) a,
       c
     where a.a_code = c.aid(+)
       and a.b_code = c.bid(+)
     group by a.a_code
    ;
      

  2.   

    这个查询基本上不会快的,因为两张表都是全表参与连接,除非A、B两表其中有一张是小表,而且两表join之后的数据量也很小,那么还可以用索引优化。
    此外,C表的连接字段必须有索引,否则这种标量子查询会翻车的
      

  3.   

    把子查询等价转换主查询,如果A B表列很多,建2个组合索引 (code,aid) (code,bid)
      

  4.   

    楼主上执行计划吧,而且这个SQL你想秒出,基本上不太可能,数据分布要非常凑巧才可以。
      

  5.   

    楼主这典型的标量子查询啊,改写吧:
    select A.code,nvl(c.sm,0), from A,B,(select aid,bid,sum(C.a) sm from C group by aid,bid ) c
     where A.code = B.code
        and a.aid=c.aid(+)
        and b.bid=c.bid(+);
    大概就这样改吧。
      

  6.   

    select A.code,(select nvl(sum(C.a),0) from C where 
    exists(select 0 from A where A.aid = C.aid) and
    exists(select 0 from B where B.aid = C.aid) 
    ) from A 
    where exists(select 0 from B where B.code = A.code) ;