0

我正在使用代码点火器。我想要一个 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')

我得到了所有产品,但 ->where('alertQuantity <=', 'totalQuantity') 没有产品。

4

3 回答 3

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 ;
于 2013-01-04T06:17:44.130 回答
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 
于 2013-01-04T06:27:19.037 回答
0

只需在您的选择语句中添加 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->db->select() 接受可选的第二个参数。如果您将其设置为 FALSE,CodeIgniter 将不会尝试使用反引号保护您的字段或表名。如果您需要复合选择语句,这很有用。

这里的文件

于 2013-01-04T05:51:04.113 回答