Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/apache/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL根据库存级别搜索受影响的行_Mysql_Sql - Fatal编程技术网

MySQL根据库存级别搜索受影响的行

MySQL根据库存级别搜索受影响的行,mysql,sql,Mysql,Sql,假设我有下表: production(rec_ID, item_ID, date, qty) usage(rec_ID, item_ID, date, qty) inventory(item_ID, stock) 使用以下示例数据: Production Rec_ID | item_ID | date | qty 1 | A | 2016-01-18 | 50 2 | A | 2016-01-19 | 50 3 | A | 20

假设我有下表:

production(rec_ID, item_ID, date, qty)
usage(rec_ID, item_ID, date, qty)
inventory(item_ID, stock)
使用以下示例数据:

Production
Rec_ID | item_ID | date | qty
1      | A       | 2016-01-18 | 50
2      | A       | 2016-01-19 | 50
3      | A       | 2016-01-20 | 50

Usage
Rec_ID | item_ID | date | qty
100    | A       | 2016-01-20 | 70

Inventory
item_ID| stock
A      | 80
正如您所见,生产中的任何东西都会增加库存,而使用中的任何东西都会减少库存。现在我有80件库存A。我想在表生产中搜索哪一行有剩余库存。规则是:从较早日期开始的生产将首先用完

使用ID 100将取自生产ID 1前70-50。剩余的20个将取自生产ID 2。因此,剩余库存为:80 30来自生产ID 2,50来自生产ID 3。如何根据库存获取生产表中受影响的行?我的想法是:

SELECT * FROM production ORDER BY date DESC
循环通过项目累计数量,直到其达到当前库存水平。例如:

current_Stock = SELECT stock FROM Inventory WHERE item_ID='A'
production_List = SELECT * FROM production WHERE item_ID='A' ORDER BY date DESC

for each production in production_List
    qty_total += production.qty
    (add each production to arraylist or something)
    if qty_total >= current_Stock
        exit for
    end if
next

(process affected rows...)

在纯SQL中有没有更优雅的方法呢?

这个查询可能是一个解决方案

    SELECT NULL AS Rec_ID,
       qty,
       NULL AS total,
       `date`
FROM cc
WHERE (@total := 0)
UNION
SELECT Rec_ID, qty, @total := @total + qty AS total, `date`
FROM
  (SELECT *
   FROM Production
   ORDER BY `date` DESC
   WHERE item_ID='A') tmp
WHERE @total <
    (SELECT stock
     FROM Inventory
     WHERE item_ID='A') ;

对这一点,Fiddle是

对于这样复杂的业务规则,纯SQL并不总是最好的答案。您可能会编写一个存储过程来执行它,但是考虑将这些东西插入数据库而不是应用程序代码的缺点。