问题描述:
     A,B两张表。A 中有id,planNumber字段.B表中有:id,aid,inputNumber.
     即A中是下达的计划数量。B中有A的id,以及已经录入的数量。
     现在操作人员登录系统,要查询上级领导下达计划(即A表信息)。
     我想这样实现:
     显示的条件是:planNumber>sum(inputNumber)的就说明还有任务没有完成,那么任务(A表信息)就显示出来。
     
     我的解决方案是:
     先查询出A中所有可用的记录List<A>,然后遍历list<A> 得到A对象a, 然后a.getId() 
     然后查询B :select sum(inputNumber) from B where aid=a.getId().
     再来和A中 planNumber比较 如果二者不等。那么把这个A对象a放到另一个List1中。页面最后遍历这个List1.
     
     这样可以实现,但是似乎和恐怖,因为没一个A对象就查询一次数据库。是不是传说的N+1问题了。
     请问有什么好的方法,比如一个sql搞定或者别的好的方法。

解决方案 »

  1.   

    have a tryselect a.id, a.planNumber 
      from A a
     where a.planNumber > (select sum(b.inputNumber) from B b
                            where b.aid = a.id);
      

  2.   

    如果B表中没有一条 aid的信息 呢?是不是就是空了。也就是当B时空的时候!这样where b.aid = a.id会有问题吗?
      

  3.   

    我觉得你的表设计的比较诡异为什么不在A表中增加一个状态字段,比如:status, 0 是未完成,1是已完成,2是失败 之类的?
      

  4.   

    如果不存在这样的B,那么返回的sum就是0,应该没问题的吧
    还是说如果不存在这样的B,就不应该选出来?
      

  5.   

    select a.id, a.planNumber 
      from A a
     where a.planNumber > ifnull((select sum(b.inputNumber) from B b
                            where b.aid = a.id),0); mysql中加个null的函数判断吧,oracle中用nvl这个
      

  6.   

    select a.id, a.planNumber 
      from A a
     where a.planNumber > (select sum(b.inputNumber) from B b
                            where b.aid = a.id);
      

  7.   

    select a.id,a.planNumber from A a,B b where a.id=b.id group by a.id having a.planNumber>sum(b.inputNumber);
    这样可以啊!
      

  8.   


    与其用1楼的子查询,不如用这个join好了。