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

INSERT ON DUPLICATE KEY UPDATE with SUM or MINUS MySQL(在带有SUM或-MYSQL的重复键更新时插入)
本文介绍了在带有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

这篇关于在带有SUM或-MYSQL的重复键更新时插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)