【问题标题】:Where SUM(table1.field) >= table2.field in joined tables连接表中的 SUM(table1.field) >= table2.field
【发布时间】:2012-12-18 13:45:58
【问题描述】:

我正在使用 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')

我得到了所有产品,但 ->where('alertQuantity

【问题讨论】:

  • 我想你想使用HAVING,而不是WHERE

标签: php mysql codeigniter join group-by


【解决方案1】:

只需在您的选择语句中添加 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 不会尝试保护您的字段或表 带有反引号的名称。如果您需要复合选择,这很有用 声明。

来自文档here

【讨论】:

  • 谢谢LearneR。我已经尝试过这一点,我一直在获得所有产品 :( 在这里加入可以吗?我不确定加入
  • 在加入后放置 where 条件
  • 累了,但是如果尝试了这个 ->where('alertQuantity where('alertQuantity
【解决方案2】:

试试这个

$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 

【讨论】:

    【解决方案3】:

    试试这个:

    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 ;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-09
      • 2012-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-19
      • 2022-12-19
      相关资源
      最近更新 更多