Php 查询交易记录中的更新库存数量

Php 查询交易记录中的更新库存数量,php,mysql,database,web,Php,Mysql,Database,Web,我的查询有问题,因为我必须从不同的库存代码中扣除产品的数量 假设客户将以20个数量购买商品代码为I0015的产品。首先,我想将12个数量扣减到库存代码ST0016中,库存将变为0,其余8个数量将扣减到库存代码ST0012中,数量扣减基于库存代码ST0012的上升日期 我如何在MySQL中查询它?非常感谢你!答案是高度赞赏的。我的表名是stocks\u table 代码是否低于解决方案 没有公共表表达式: update stocks_table st join( select * from(

我的查询有问题,因为我必须从不同的库存代码中扣除产品的数量

假设客户将以20个数量购买商品代码为I0015的产品。首先,我想将12个数量扣减到库存代码ST0016中,库存将变为0,其余8个数量将扣减到库存代码ST0012中,数量扣减基于库存代码ST0012的上升日期

我如何在MySQL中查询它?非常感谢你!答案是高度赞赏的。我的表名是stocks\u table


代码是否低于解决方案

没有公共表表达式:

update stocks_table st
join(
  select * from(
    select *
    ,case when cumulsum <= TotalRequiredQuantity then 0 else cumulsum-TotalRequiredQuantity end NewQuantity 
     from(
       select *, 20 TotalRequiredQuantity,/*Set valid quantitity*/
          sum(stock_quantity) over(partition by item_code order by stock_expired) cumulsum
       from stocks_table
       where item_code = 'I0015'/*Set valid item_code*/
    )q
  )q1
  where stock_quantity>=NewQuantity
)cte on st.id=cte.id
set st.stock_quantity = NewQuantity

您是否可以显示到目前为止您拥有的代码,以便其他人可以根据您的代码进行构建。请查看,您希望通过查询来更新各种库存中的剩余数量,根据过期优先级选择,给定产品的id和购买的数量。@user1767316是的,先生。先生,我遇到此错误,我不知道原因。SQL错误1064:您的SQL语法有错误;查看与您的MariaDB服务器版本相对应的手册,了解使用near'cte as select*from select*的正确语法,例如cumulsum此解决方案适用于MySQL 8.0+谢谢,先生,我认为查询是正确的,但当我在Heidi SQL中测试时,我在一个分区中发现了一个错误。sir@Nick,这是我的问题,你能给我一些想法,我该如何把它转换成小组。非常感谢。
update stocks_table st
join(
  select * from(
    select *
    ,case when cumulsum <= TotalRequiredQuantity then 0 else cumulsum-TotalRequiredQuantity end NewQuantity 
     from(
       select *, 20 TotalRequiredQuantity,/*Set valid quantitity*/
          sum(stock_quantity) over(partition by item_code order by stock_expired) cumulsum
       from stocks_table
       where item_code = 'I0015'/*Set valid item_code*/
    )q
  )q1
  where stock_quantity>=NewQuantity
)cte on st.id=cte.id
set st.stock_quantity = NewQuantity