我有一个MySQL数据库,其中包含一个订单表和包含可用库存的零件编号表。
例如
==Orders Table==
part_number
order_date
qty
==Stock Table==
part_number
stock_qty
假设可用库存将分配给最近的订单,我如何从订单表中选择没有库存的行来覆盖它们。
订单表可能有1.5到200万条记录,因此将整个数据集读入内存并首先使用PHP进行处理并不理想。
===更新和最终答案===
戈登的回答给了我足够的信息,以获得对我有用的确切结果。我在下面列出了。
select * from (
select o.*,s.stock_qty,(@netted_stock := if(@pn = o.part_number,@netted_stock-sumqty,s.stock_qty-sumqty)) as netted_stock
from (select o.*,
(@sumqty := if(@pt = part_number, @sumqty + qty,
if(@pt := part_number, qty, qty)
)
) as sumqty
from orders o cross join
(select @pn := -1, @sumqty := 0, @netted_stock:= 0) params
order by part_number, order_date desc
) o join
stock s
on o.part_number = s.part_number
) s
这是它给我的结果。
答案 0 :(得分:1)
您需要每个订单的累计库存总和。你可以用变量得到它。其余的只是简单的逻辑:
select o.*
from (select o.*,
(@sumqty := if(@pt = part_number, @sumqty + qty,
if(@pt := part_number, qty, qty)
)
) as sumqty
from orders o cross join
(select @pn := -1, @sumqty := 0) params
order by part_number, order_date desc
) o join
stock s
on o.part_number = s.part_number
where s.stock_qty < o.sumqty;