Reputation: 313
I was searching real hard for an answer but couldn't find one
I have this table
and I am using this query to update it (this query is a must because I have dynamic inputs from my frontend so I can update multiple rows)
INSERT INTO main_inventory(name,sellingPrice,purchasePrice,averagePrice,totalQuantity) VALUES("test1",20,5,27.5,23),VALUES("test2",20,5,27.5,50)
ON DUPLICATE KEY UPDATE name = VALUES(name),sellingPrice = VALUES(sellingPrice),purchasePrice = VALUES(purchasePrice),averagePrice = VALUES(averagePrice),totalQuantity = VALUES(totalQuantity)
thing is, if I run this query above. The table should be updated but I want the totalQuantity column to be added so the value of test1 should be 46 and test2 will be 73. I have no idea what to do
name column is unique and a key
I am doing the query with nodejs
let query4 = `INSERT INTO main_inventory(name,sellingPrice,purchasePrice,averagePrice,totalQuantity) VALUES`
for(let x=0;x<main_items.length;x++){
if(x+1 == main_items.length){
query4 = query4+`("${main_items[x].item}",${main_items[x].sellingPrice},${main_items[x].purchasePrice},${main_items[x].averagePrice},${main_items[x].quantity})
ON DUPLICATE KEY UPDATE name = VALUES(name),sellingPrice = VALUES(sellingPrice),purchasePrice = VALUES(purchasePrice),averagePrice = VALUES(averagePrice),totalQuantity = VALUES(totalQuantity)`
}else{
query4 = query4+`("${main_items[x].item}",${main_items[x].sellingPrice},${main_items[x].purchasePrice},${main_items[x].averagePrice},${main_items[x].quantity}),`
}
}
Upvotes: 1
Views: 558
Reputation: 222622
You can refer to current value of column that you insert into in the UPDATE
part of the query, like:
INSERT INTO main_inventory(name, sellingPrice, purchasePrice, averagePrice, totalQuantity)
VALUES ('test1', 20, 5, 27.5, 23), ('test2', 20, 5, 27.5, 50)
ON DUPLICATE KEY UPDATE
name = VALUES(name),
sellingPrice = VALUES(sellingPrice),
purchasePrice = VALUES(purchasePrice),
averagePrice = VALUES(averagePrice),
totalQuantity = totalQuantity + VALUES(totalQuantity) -- add to the original value
Upvotes: 4