简体   繁体   中英

Update multiple rows with one value and divide it to the different row in single SQL query

Basically I have two tables itemTable and stockTable, every time I add a stock, I will get the foreign key for itemId and add it in stockTable with quantity.

I want to update the stockquantity in stockTable every time the customer will buy a product.

PROBLEM: For example the customer will buy 7 shirt: SO FIRST WILL UPDATE ON THE STOCKID (3) QUANTITY OF 4 SECOND WILL UPDATE THE STOCKID (6) QUANTITY OF 3

SO THE TOTAL STOCKS OF SHIRT IS 3 AFTER UPDATING THE QUANTITY

THE STOCKID (3) WILL BECOME 0 THE STOCKID (6) WILL BECOME 3

HOW DO I QUERY THAT IN SQL. THANK YOU!

TOTAL STOCKS: (Base on the same itemName)
SHOES - 5
SHIRT - 10
BALL  - 15

stockTable

stockId   itemId    stockQuantity  stockOut
1           35             5
3           89             4 
6           11             6
14          87             15

itemTable

itemId    itemName     itemSellPrice  supplierName
35           shoes          50          Jason
89           shirt          40          Jacob
11           shirt          65          Max
87           ball           150         Sam

First of all you need to identify the itemId(s) that must be updated, they are in the result of:

SELECT itemId FROM itemTable WHERE itemName = 'shirt'

Having said that the update query will look like this:

UPDATE stockTable SET ... WHERE itemId IN (SELECT itemId FROM itemTable WHERE itemName = 'shirt')

Obviously now we need to update the quantities, this must be done progressively until the order is complete starting from the lowerst itemId (for istance):

SELECT IF(stockQuantity>7,@remaining_qty:=stockQuantity-7,@remaining_qty:=@remaining_qty-stockQuantity) AS `remaining_qty` FROM stockTable WHERE itemId IN (SELECT MIN(itemId) FROM itemTable WHERE itemName = 'shirt';

UPDATE stockTable SET stockQuantity=IF(stockQuantity>7,stockQuantity-7,0) WHERE itemId IN (SELECT MIN(itemId) FROM itemTable WHERE itemName = 'shirt');

After that you can check the variable @remaining_qty, and reapeat the stuff until @remaining_qty>0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM