我正在尝试根据列的总和检索数据子集。目标是发布延期交货商品的脚本。假设我们有 100 种 BO 产品并有 50 种库存。我想更新订单数量总和 < 50 的最旧订单。比如:
示例架构:
Orders Table:
order_id, order_date
order_products Table:
order_product_id, order_id, product_id, product_status, ordered_quantity
select * from products
where products_id=1234
and status=1
and sum(products_qty) < 50;
其中 sum(products_qty) 是总返回数量,而不仅仅是单个行。不确定单个查询甚至子查询是否可行,但我想我会先问这里的专家。我试图避免返回所有行,然后手动计数直到达到限制。
最佳答案
你需要使用 GROUP by 和 Having
select * from products
where products_id=1234
and status=1
group by YourGroupingFields
Having sum(products_qty) < 50;
根据您的信息:
select product_id from products
where status=1
group by product_id
Having sum(products_qty) < 50;
返回总数量少于50的product_id
关于php - 根据列的总和返回行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3637463/