我正在使用codeigniter。我想要一个where子句来获取totalQuantity小于alterQuantity的产品。我在select子句中使用sum来获得totalQuantity。
$this->db->select("products.id as productid, products.code, products.name, products.unit, products.cost, products.price, sum(whs_products.quantity) as totalQuantity, products.alert_quantity as alertQuantity")
->from('products')
->where('alertQuantity <=', 'totalQuantity')
->join('whs_products', 'whs_products.product_id=products.id', 'left')
->group_by("products.id");
$this->db->get();
我不确定如何获得所需的产品:( 编辑 如果试过这个
->where('alertQuantity <=', 'totalQuantity')
我得到所有产品但是 - &gt; where('alertQuantity&lt; =','totalQuantity')没有产品。
答案 0 :(得分:0)
只需在select语句中添加FALSE并尝试
$this->db->select("products.id as productid, products.code, products.name, products.unit, products.cost, products.price, sum(whs_products.quantity) as totalQuantity, products.alert_quantity as alertQuantity",FALSE)
$ this-&gt; db-&gt; select()接受可选的第二个参数。如果你设置 它为FALSE,CodeIgniter不会试图保护你的领域或表 带反叛的名字。如果您需要复合选择,这非常有用 言。
来自文件here
答案 1 :(得分:0)
试试这个:
SELECT p.id AS productid, p.code, p.name, p.unit, p.cost, p.price, wp.quantity AS totalQuantity, p.alert_quantity AS alertQuantity
FROM products p
LEFT JOIN (SELECT product_id, SUM(quantity) quantity
FROM whs_products GROUP BY product_id) wp ON wp.product_id = p.id AND p.alert_quantity <= quantity ;
答案 2 :(得分:0)
试试这个
$this->db->select("products.id as productid, products.code, products.name, products.unit, products.cost, products.price, sum(whs_products.quantity) as totalQuantity, products.alert_quantity as alertQuantity")
->from('products')
->join('whs_products', 'whs_products.product_id=products.id', 'left')
->where('alertQuantity <= totalQuantity')
->group_by("products.id");
$this->db->get();
echo $this->db->last_query();exit; //to check the query generated is correct or not