从销售的商品中查找产品成本的总和

时间:2011-08-15 21:43:00

标签: mysql codeigniter

我有一个CodeIgniter网站,我正在为零售商建立一些统计数据。我需要找到所有销售产品的product_cost总和,其中产品'category1'等于1.

下面的数据结构显示'产品'和'order_items',顾名思义它包含所有已售商品。

products
---
product_id
category1
product_price
product_cost

order_items
---
order_id
product_id
quantity

所以基本上我试图在CodeIgniter中获取正确的SQL语句,以便在我的orders_model中形成一个函数。

感谢任何帮助。 :)

1 个答案:

答案 0 :(得分:0)

假设您没有使用Active Record而只想要一个简单的查询,这应该会为您提供所需的结果:

SELECT SUM(product_cost) AS total_cost FROM products RIGHT JOIN order_items ON products.product_id = order_items.product_id WHERE products.category1 = 1

Active Record将如下所示:

$this->db->select('SUM(product_cost) AS total_cost');
$this->db->from('products');
$this->db->join('order_items', 'products.product_id = order_items.product_id', 'right');
$this->db->where('products.category1',1);
$query = $this->db->get();
相关问题