因为您通过项目主数据(产品表)将采购活动加入到销售活动中。因此,总和中包含的采购行数取决于您拥有的销售行数;反之亦然。
您需要将这些查询分离为在视图中组合的单独 SQL 语句,或者您可以使用 SQLUNION ALL
组合两条语句:一条用于购买,一条用于销售。
两种说法:
$this->alerts
->select('products.id as productid, products.code as code, products.name, products.price, sum(purchase_items.quantity)')
->from('products');
$this->alerts->join('purchase_items', 'products.id = purchase_items.product_id');
$this->alerts->group_by("products.id");
echo "Total Purchases";
echo $this->alerts->generate();
$this->alerts
->select('products.id as productid, products.code as code, products.name, products.price, sum(sale_items.quantity)')
->from('products');
$this->alerts->join('sale_items', 'products.id = sale_items.product_id');
$this->alerts->group_by("products.id");
echo "Total Sales";
echo $this->alerts->generate();
或者,在 SQL 中:
$results = $this->db->query('
SELECT products.id as productid, products.code as code, products.name, products.price, ''Purchase'' as transaction, sum(purchase_items.quantity)
FROM products
JOIN purchase_items ON products.id = purchase_items.product_id
GROUP BY products.id
UNION ALL
SELECT products.id as productid, products.code as code, products.name, products.price, ''Sale'' as transaction sum(sales_items.quantity)
FROM products
JOIN sales_items ON products.id = sales_items.product_id
GROUP BY products.id')->result_array();
// Echo $results....
编辑:
我不完全确定您的Alerts
模型中有什么,但是在您修改后的查询中,您将 SQL 语句分配给变量两次$products
但不执行语句?
还要确保您的警报模型扩展CI_Model
。
在更标准的 Codeigniter 语法中,我会做这样的事情:
// In Controller, assuming the Alerts model is loaded, and using method chaining.
// Get all sales. By the way, you normally have to group on all columns *not* being aggregated. You might
// get unexpected results by grouping on price, unless the price never changes.
$this->alerts->select('products.id as productid, products.code, products.name, products.price, sum(sale_items.quantity) as quantity')
->from('products')
->join('sale_items', 'products.id = sale_items.product_id')
->group_by('products.id, products.code, products.name, products.price');
$sales = $this->alerts->get()->result_array();
// Get all purchases
$this->alerts->select('products.id as productid, products.code, products.name, products.price, sum(purchase_items.quantity) as quantity')
->from('products')
->join('purchase_items', 'products.id = purchase_items.product_id')
->group_by(products.id, products.code, products.name, products.price);
$purchases = $this->alerts->get()->result_array();
// Put it all together
$products = array_merge($sales, $purchases);
// And now do something with your combined results $products. Send to view, echo etc.