在我的sql codeigniter中相互添加减去数据库字段

时间:2015-05-19 07:04:46

标签: php mysql codeigniter

这是我的查询

function getInventoryAvailableQty($product_id,$warehouse_id,$location_id) {

   $this->db->select_sum('quantity','addqty');
   $this->db->select_sum('total_cost','addcost');
   if($warehouse_id)
   $this->db->where('warehouse_id',$warehouse_id);
   if($location_id)
   $this->db->where('location_id',$location_id);
   if($product_id)
   $this->db->where('product_id',$product_id);
   $this->db->where('inventory_type','add');
   $query = $this->db->get($this->tablename);
   $resultAdd = $query->row();

   $this->db->select_sum('quantity','removeqty');
   $this->db->select_sum('total_cost','removecost');
   if($warehouse_id)
   $this->db->where('warehouse_id',$warehouse_id);
   if($location_id)
   $this->db->where('location_id',$location_id);
   if($product_id)
   $this->db->where('product_id',$product_id);
   $this->db->where('inventory_type','remove');
   $query1 = $this->db->get($this->tablename);
   $resultRemove = $query1->row();

   $data['imeicost'] = $resultAdd->addcost-$resultRemove->removecost;
   $data['availableQty'] = $resultAdd->addqty-$resultRemove->removeqty;
   return $data;

}

我想在单个查询中执行此操作。因为我想在此添加分页,我该怎么做才能建议

1 个答案:

答案 0 :(得分:0)

不确定是否可以使用CI Active记录执行此操作,但您可以编写SQL查询并使用$this->db->query($query)

运行它

您的查询可能是这样的:

SELECT
    *
FROM
    (
        SELECT
            SUM(quantity) AS addqty_add,
            SUM(total_cost) AS addcost_add
        FROM
            tbName
        WHERE
            warehouse_id = 2
        AND inventory_type = 'add'
    ) AS tb1,
    (
        SELECT
            SUM(quantity) AS addqty_remove,
            SUM(total_cost) AS addcost_remove
        FROM
            tbName
        WHERE
            warehouse_id = 2
        AND inventory_type = 'remove'
    ) AS tb2