【问题标题】:INSERT ON DUPLICATE KEY UPDATE with SUM or MINUS MySQL使用 SUM 或 MINUS MySQL 插入重复键更新
【发布时间】:2020-04-11 17:14:46
【问题描述】:

我一直在努力寻找答案,但找不到答案

我有这张桌子

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

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。我不知道该怎么做

name 列是唯一的并且是一个键

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

            }
        }

【问题讨论】:

    标签: javascript mysql node.js sql-update sql-insert


    【解决方案1】:

    您可以在查询的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
    

    【讨论】:

      猜你喜欢
      • 2017-12-24
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2014-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多