为什么(My)SQL中的Sum()函数返回我期望的值的两倍?

时间:2018-04-09 13:05:58

标签: php mysql sql zend-framework2

我需要来自两个不同表格的两个不同列的总和,即tbl_billtbl_receipt

tbl_receipt

 id receipt_no  member_id   receipt_amount
 1  21001         21        20500
 2  21002         21        200

TBL_MEMBER表

  id    name
  21    priya

tbl_invoice

 id bill_no  order_id   member_id     bill_value
 1  30001       30          21          20928
 2  0002501     25          21          12030

我想以这种方式回答

member_id  member_name  receipt_sum  bill_sum   
21         priya        20700         32958

我尝试了左连接,但它将和值加倍。任何人都可以帮助我吗?

$adapter = $this->tableGateway->getAdapter();
       $orderTable = new TableGateway('tbl_receipt', $adapter);
       $sqlSelect = $orderTable->getSql()->select();
       $sqlSelect->columns(array('id'=>'id','bill_amount'=>'bill_total','sum_receipt_amount'=>new \Zend\Db\Sql\Expression('SUM(tbl_receipt.receipt_amount)'))); 
       $sqlSelect->join('tbl_member','tbl_member.id = tbl_receipt.member_id', array('member_id'=>'id','member_name'=>'name'),'LEFT');
     //  $sqlSelect->join('tbl_receipt','tbl_receipt.member_id = tbl_bill.member_id', array('receipt_id'=>new \Zend\Db\Sql\Expression('(tbl_receipt.receipt_amount)')),'LEFT');


       $sqlSelect->group('tbl_member.id');
       $resultSet = $orderTable->selectWith($sqlSelect);
        //echo"<pre>";

   // print_r($resultSet); die;
  return $resultSet;

1 个答案:

答案 0 :(得分:2)

在SQL中你应该在sum

的结果上保持联接
select m.id, m.name,t1.sum_amount, t2.sum_total
from tbl_member m  
left join (
  select member_id, sum(receipt_amount) sum_amount 
  from tbl_receipt
  group by member_id
) t1 on t1.member_id = m.member_id 
left  join (
  select member_id, sum(total) sum_total
  from tbl_invoice
  group by member_id
) t2  on t2.t1.member_id = m.member_id