因为您正在通过商品主数据(产品表)将采购活动加入到销售活动中。因此,总额中包含的采购行数取决于您有多少行销售额;反之亦然。
您需要将这些查询分开为您在视图中组合的单独SQL语句,也可以使用SQL UNION 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
模式,但在你修改查询您正在向变量$products
分配两次SQL语句但不执行语句?
此外,请确保您的警报模型延伸CI_Model
。
更笨的标准语法,我会做这样的事情:
// 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.
我认为[我回答这个问题(http://stackoverflow.com/questions/13651446/multiple-left-joins如何/ 13652061#13652061)应该告诉你为什么...这是因为你没有考虑组合套件,基本上我知道 – 2013-02-08 18:10:17