I have a table ITEM(id, description) and STOCK(id, qty, timestamp, item_id) where item_id is a foreign key mapped to ITEM.
I am presenting the ITEM table with column qty that I get when adding the qty of all the stock of an item.
Now, I need to subtract items. In order to do that, I need to subtract from the qty of stock.
What is the query for this given that the stock with the oldest timestamp should be prioritized to be subtracted and that once the qty reaches 0, the remaining should be subtracted from the other stocks?
P.S.: I'm planning to create a procedure for MySQL so that I'll call it when I need to do that.