我在CodeIgniter中有以下MY-SQL查询,我正在尝试 [sub_product_price] * [数量] 的乘法并将其显示为乘以。任何人都可以帮助我。我查看了CodeIgniter用户指南,但找不到与此相关的任何内容。
感谢!!!!
function product_profit_chart(){
$this->db->select(array(
'tbl_sub_products.sub_product_name',
'tbl_sub_products.sub_product_id',
'tbl_sub_products.sub_product_price',
'SUM(tbl_order_products.quantity) as quantity'
));
$this->db->from('tbl_order_products');
$this->db->join('tbl_order_product_details', 'tbl_order_product_details.order_id=tbl_order_products.order_id','LEFT');
$this->db->join('tbl_sub_products', 'tbl_sub_products.sub_product_id=tbl_order_products.product_id','LEFT');
$this->db->group_by('tbl_sub_products.sub_product_id');
$this->db->where('tbl_order_product_details.order_status', 'completed');
$query = $this->db->get();
return $query->result();
}
返回上述查询的数组。
[1] => stdClass Object
(
[sub_product_name] => chocolate cake 500G
[sub_product_id] => SP001
[sub_product_price] => 1000.00
[quantity] => 14
)
[2] => stdClass Object
(
[sub_product_name] => Sausage Bun
[sub_product_id] => SP002
[sub_product_price] => 50.00
[quantity] => 16
)
答案 0 :(得分:0)
按如下方式更改您的功能:
function product_profit_chart(){
$this->db->select(array(
'tbl_sub_products.sub_product_name',
'tbl_sub_products.sub_product_id',
'tbl_sub_products.sub_product_price',
'SUM(tbl_order_products.quantity) as quantity',
'SUM(tbl_sub_products.sub_product_price * quantity) as amount'
));
$this->db->from('tbl_order_products');
$this->db->join('tbl_order_product_details', 'tbl_order_product_details.order_id=tbl_order_products.order_id','LEFT');
$this->db->join('tbl_sub_products', 'tbl_sub_products.sub_product_id=tbl_order_products.product_id','LEFT');
$this->db->group_by('tbl_sub_products.sub_product_id');
$this->db->where('tbl_order_product_details.order_status', 'completed');
$query = $this->db->get();
return $query->result();
}
希望这会对你有所帮助。
答案 1 :(得分:0)
只需在执行乘法的位置再添加一个选择项:
$this->db->select(array(
'tbl_sub_products.sub_product_name',
'tbl_sub_products.sub_product_id',
'tbl_sub_products.sub_product_price',
'SUM(tbl_order_products.quantity) as quantity',
/* add this column: */
'SUM(tbl_order_products.quantity) * tbl_sub_products.sub_product_price as total'
));
See this demo (不是Codeigniter Active Record,但显示工作查询逻辑)
答案 2 :(得分:0)
未经测试,它使用别名进行查询并使用select_sum()
而不是在select查询中编写它
function product_profit_chart(){
$this->db->select('sub_product_name', 'sub_product_id', 'sub_product_price');
$this->db->select_sum('sub_prod.sub_product_price * prod.quantity as quantity');
$this->db->from('tbl_order_products prod');
$this->db->join('tbl_order_product_details prod_details', 'prod_details.order_id=prod.order_id','LEFT');
$this->db->join('tbl_sub_products as sub_prod', 'sub_prod.sub_product_id=prod.product_id','LEFT');
$this->db->group_by('sub_prod.sub_product_id');
$this->db->where('prod_details.order_status', 'completed');
$query = $this->db->get();
return $query->result();
}