【问题标题】:Query for update stock quantity in transaction [closed]查询交易中的更新库存数量[关闭]
【发布时间】:2023-03-28 22:15:01
【问题描述】:

我的查询有问题,因为我必须从不同的 stock_code 中扣除产品的数量。

假设客户将以 item_code (I0015) 购买 20 个数量的产品。首先我要在stock_code(ST0016)中减去12个数量,库存变为0,剩下的8个数量在stock_code(ST0012)中扣除,数量的扣除是根据stock_expired的升序。

如何在 MySQL 中查询?太感谢了!高度赞赏答案。我的表名是stocks_table

【问题讨论】:

  • 您能否展示您目前拥有的代码,以便其他人可以在您的代码上构建。
  • 所以你想要一个查询来更新各种库存的剩余数量,根据到期优先级选择,给定产品的 ID 和购买的数量。
  • @user1767316 是的先生。

标签: php mysql database web


【解决方案1】:

代码是否低于解决方案 (fiddle)?

with cte as(
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)

update stocks_table st
join cte on st.id=cte.id
set st.stock_quantity = NewQuantity

没有公用表表达式:

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

【讨论】:

  • 先生,我收到了这个错误,我不知道为什么。 SQL 错误 (1064):您的 SQL 语法有错误;检查与您的 MariaDB 服务器版本相对应的手册,以在第 1 行的 'cte as( select * from( select *, case when cumulsum
  • 本方案适用于 MySQL 8.0+
  • 谢谢,先生,我认为查询是正确的,但是当我在 Heidi SQL 中测试时,我在一个分区中遇到了一个错误。
  • @Nick 先生,这是我的问题,stackoverflow.com/questions/60576264/…,您能否告诉我如何将其转换为 GROUP BY。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-15
  • 2011-07-17
  • 2019-05-16
  • 2021-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多