查询返回单个记录,如果有总和

时间:2015-10-26 10:51:29

标签: mysql codeigniter

我想从表中检索整个记录以及它的总和记录,但问题是当我在其中使用mysql sum()函数时它只返回一条记录并且当我删除mysql sum()函数时返回整个记录问题是总和我谷歌它但无法找到相关的材料再次。 我正在使用codeigniter活动记录来检索数据,请指出我在哪里制作mistak.ty

这是我的模特函数。

function get_soorh_jama($start_date,$end_date)
{
    $where=array('pe.pur_inv_date >='=>$this->date);
    //$this->db->select_sum('si.chungi');
    $this->db->select('pe.*,px.*,kt.name');
    $this->db->from('purchase_invoice as pe');
    $this->db->join('khata as kt','pe.supplier_id=kt.id');
    $this->db->join('purexpenses as px','pe.pur_inv_id=px.inv_id');
    $this->db->select_sum('pe.nags','sold_nags');
    $this->db->where($where);
    $query=$this->db->get();
    echo $this->db->last_query();
    return $query->result();
}

这是普通查询的样子。

SELECT `pe`.*, `px`.*, `kt`.`name`, SUM(`pe`.`nags`) AS sold_nags FROM (`purchase_invoice` as pe) JOIN `khata` as kt ON `pe`.`supplier_id`=`kt`.`id` JOIN `purexpenses` as px ON `pe`.`pur_inv_id`=`px`.`inv_id` WHERE `pe`.`pur_inv_date` >= '10/26/2015'

1 个答案:

答案 0 :(得分:1)

使用group by pur_inv_id

SELECT `pe`.*, `px`.*, `kt`.`name`, SUM(`pe`.`nags`) AS sold_nags 
FROM (`purchase_invoice` as pe) JOIN `khata` as kt 
ON `pe`.`supplier_id`=`kt`.`id` JOIN `purexpenses` as px 
ON `pe`.`pur_inv_id`=`px`.`inv_id` WHERE `pe`.`pur_inv_date` >= '10/26/2015' 
group by pur_inv_id