codigniter数据库查询替换现有数据库查询

时间:2017-02-05 19:48:51

标签: php mysql database codeigniter

$this->db->select('SUM( COALESCE( purchase_unit_cost, 0 ) * quantity ) AS cost, SUM( COALESCE( sale_unit_price, 0 ) * quantity ) AS sales, SUM( COALESCE( purchase_net_unit_cost, 0 ) * quantity ) AS net_cost, SUM( COALESCE( sale_net_unit_price, 0 )*quantity ) AS net_sales', FALSE);

if($date){
$this->db->where('costing.date', $date);
}
$q = $this->db->get('costing');
if ($q->num_rows() > 0) {
            return $q->row();
}

我想用以下代码替换上面的代码:

select SUM( COALESCE( sma_costing.purchase_unit_cost, 0 ) * sma_costing.quantity ) AS cost, SUM( COALESCE( sma_costing.sale_unit_price, 0 ) * sma_costing.quantity ) AS sales, SUM( COALESCE( sma_costing.purchase_net_unit_cost, 0 ) * sma_costing.quantity ) AS net_cost, SUM( COALESCE( sma_costing.sale_net_unit_price, 0 ) * sma_costing.quantity ) AS net_sales
from  sma_costing
right join sma_sale_items on (sma_sale_items.id=sma_costing.sale_item_id and sma_sale_items.quantity=sma_costing.quantity)
left join sma_sales on sma_sale_items.sale_id=sma_sales.id
where sma_costing.date='$date'

尝试过codeigniter但没有显示任何结果

$this->db->select('SUM( COALESCE( purchase_unit_cost, 0 ) * quantity ) AS cost, SUM( COALESCE( sale_unit_price, 0 ) * quantity ) AS sales, SUM( COALESCE( purchase_net_unit_cost, 0 ) * quantity ) AS net_cost, SUM( COALESCE( sale_net_unit_price, 0 )*quantity ) AS net_sales', FALSE);if ($date) {$this->db->where('costing.date', $date);}elseif ($month) {$this->load->helper('date'); $last_day = days_in_month($month, $year); $this->db->where('costing.date >=', $year.'-'.$month.'-01 00:00:00');$this->db->where('costing.date <=', $year.'-'.$month.'-'.$last_day.' 23:59:59');} if ($warehouse_id) {
        $this->db->join('sales', 'sales.id=costing.sale_id')
        ->where('sales.warehouse_id', $warehouse_id);
    }$q = $this->db->get('costing'); if ($q->num_rows() > 0) {
        return $q->row();}return false;   

这是我调整它的代码

2 个答案:

答案 0 :(得分:0)

尝试使用$this->db->query()

$this->db->query("SELECT SUM( COALESCE( sma_costing.purchase_unit_cost, 0 ) * sma_costing.quantity ) AS cost, SUM( COALESCE( sma_costing.sale_unit_price, 0 ) * sma_costing.quantity ) AS sales, SUM( COALESCE( sma_costing.purchase_net_unit_cost, 0 ) * sma_costing.quantity ) AS net_cost, SUM( COALESCE( sma_costing.sale_net_unit_price, 0 ) * sma_costing.quantity ) AS net_sales
                FROM  sma_costing
                RIGHT JOIN sma_sale_items on (sma_sale_items.id=sma_costing.sale_item_id AND sma_sale_items.quantity=sma_costing.quantity)
                LEFT JOIN sma_sales on sma_sale_items.sale_id=sma_sales.id
                WHERE sma_costing.date='$date' ");

答案 1 :(得分:0)

您可以使用像这样的

脚本来使用查询绑定
$this->db->query($query, $bind /* as array */);