Skip to content
Advertisement

How to deduct sold quantity from stock tables in MySQL

I have two mysql tables. The two tables with the sample data are as follows.

By this I want to build up a update query. This should deduct the quantity of the items in the sales table from the stock table. If such a query can be created in mysql it should be updated in ascending order on the stock_id in the stock table.

If such an update query can be built, based on the data in the two tables above, I expect the result to be as follows.

Any help would be highly appreciated.

Advertisement

Answer

Here is my understanding of the problem:

According to your stock table, there are 06 quantity in hand of item_id #1

Then again a new stock comes in and new entry is made in stock table. For example, another 28 quantity has come in, so the table would look like as follows:

Now, there are 6 + 28 = 34 quantity in stock. According to your sales data, you have sold twice of item_id #1. As first time 20 items and next time 2 items. Since we have more quantity in stock than sold quantity, so we can do both sales.

As you mentioned in your question, now we have to adjust the sold items from stock in ascending order on the stock_id in the stock table. Of course here you are using the First In First Out (FIFO) method to maintain your stock. This method works in such a way that you have to clear stock which has come first.

Now it would not be a very simple SQL which can update the stock in hand, however this is my attempt.

My query can only be run once for a set of sales data as each time it reduces the stock and updates the stock table (as you requested). Not the best method as it means storing derived data.

The following is the result of running the above query one at a time each time data is added to the sales table.

Starting Stock

Result 01 – After 1st sale

Result 02 – After 2nd sale

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement