在带有SUM或-MYSQL的重复键更新时插入

我非常努力地寻找答案,但没有找到

我有这张表

我正在使用这个查询来更新它(这个查询是必须的,因为我有来自前端的动态输入,所以我可以更新多行)

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)
问题是,如果我运行上面的查询。应该更新该表,但我希望添加totalQuantity列,因此Test1的值应该是46,而Test2的值应该是73。我不知道该怎么办

名称列是唯一的,并且是键

我正在使用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}),`

            }
        }

解决方案

您可以引用您在查询的UPDATE部分插入的列的当前值,如:

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

相关文章