我可以使用select字段中的somename作为where子句中的somename吗?

时间:2013-01-04 08:58:24

标签: php mysql codeigniter

我正在尝试使用totalQuantity小于alterQuantity的产品。

$this->db
->select("products.id as productid, products.code as code, products.name, products.unit, products.price, sum(warehouses_products.quantity) as totalQuantity, products.alert_quantity as alertQuantity")
->from('products')
->where('alertQuantity >=', 'totalQuantity')
->join('warehouses_products', 'products.id=warehouses_products.product_id, 'left')
->group_by("products.id");

我收到错误,未知列'alertQuantity'在'where子句'如果我使用products.alert_quantity在where子句中获取alertTantity_quantity 'where子句'中的'未知列'totalQuantity' 这个我不知道怎么改变,因为这是数量的总和。你能帮我解决这个问题吗?

我的问题: 我选择alert_quantity作为alertQuantity,sum(数量)作为totalQuantity

我可以在where子句中使用alterQuantity和totalQuantity吗?

表格结构

产品

id,代码,名称,单位,价格,alert_quantity

warehouses_products

id,product_id,warehouse_id,数量


实测值  我不能使用totalQuantity有没有其他的想法,我如何比较products.alert_quantity和sum(warehouses.products.quantity)?

2 个答案:

答案 0 :(得分:0)

试试这个::

select 
products.id as productid, 
products.code as code, 
products.name, products.unit, 
products.price, 
sum(products.alert_quantity) as totalQuantity, 
products.alert_quantity as alertQuantity
from products

LEFT join warehouses_products on products.id=warehouses_products.product_id
where products.alert_quantity>= totalQuantity
group_by products.id

答案 1 :(得分:0)

尝试使用select的第二个参数,比如 变化

$this->db
->select("products.id as productid, products.code as code, 
products.name, products.unit, products.price, 
sum(warehouses_products.quantity) as totalQuantity, 
products.alert_quantity as alertQuantity")

$this->db
->select("products.id as productid, products.code as code, 
products.name, products.unit, products.price, 
sum(warehouses_products.quantity) as totalQuantity, 
products.alert_quantity as alertQuantity", FALSE)

并关闭连接部分中的引号

编辑,尝试重新排序您的语句,例如:

$this->db
->select("products.id as productid, products.code as code, products.name, products.unit, products.price, sum(warehouses_products.quantity) as totalQuantity, products.alert_quantity as alertQuantity", FALSE)
->from('products')
->join('warehouses_products', 'products.id=warehouses_products.product_id', 'left')
->where('alertQuantity >=', 'totalQuantity')
->group_by("products.id");