【问题标题】:mySQL update exiting value by variable amountmySQL 按可变数量更新现有值
【发布时间】:2018-04-09 21:11:12
【问题描述】:

我在一个名为 stock_quantity 的表中有一个列。每条记录都有一个特定的数字,表示当前库存的数量。我正在使用节点查询器提示用户输入要添加到现有 stock_quantity 记录的金额。我想更新 stock_quantity 的特定记录,而不必查询数据库来获取现有的库存数量。有可能还是我必须做单独的查询来获取特定的现有数量,然后在更新查询之前进行数学运算?

如果我使用以下 sn-p,我可以按特定数量(例如 1)更新记录:

connection.query("UPDATE product SET stock_quantity = stock_quantity + 1 
WHERE ?",
    [
      {
        item_id: itemID
      }
    ],
    function(err, result) {
      if(err) {
        console.log(err);
      }

      console.log("Stock Quantity of item " + itemID + " increased by " + 
      addQty + " units.");
    }
  );

但是,如果我尝试将 stock_quantity 的记录更新为可变数量,则会出现错误。我尝试了以下方法:

var itemID = parseInt(answer.item_id);
var addQty = parseInt(answer.add_qty);

if(typeof addQty === "number") {

  connection.query("UPDATE product SET stock_quantity = stock_quantity + 
  addQTY WHERE ?",
    [
      {
        item_id: itemID
      }
    ],
    function(err, result) {
      if(err) {
        console.log(err);
      }

      console.log(result);

      console.log("Stock Quantity of item " + itemID + " increased by " + 
      addQty + " units.");
    }
  );
}  

我也试过这个:

var itemID = parseInt(answer.item_id);
var addQty = parseInt(answer.add_qty);

if(typeof addQty === "number") {

  connection.query("UPDATE product SET ? WHERE ?",
    [
      {
        stock_quantity: stock_quantity + addQty
      },      
      {
        item_id: itemID
      }
    ],
    function(err, result) {
      if(err) {
        console.log(err);
      }

      console.log(result);

      console.log("Stock Quantity of item " + itemID + " increased by " + 
      addQty + " units.");
    }
  );
}

最后,我尝试了这个:

var itemID = parseInt(answer.item_id);
var addQty = parseInt(answer.add_qty);

if(typeof addQty === "number") {

  connection.query("UPDATE product SET stock_quantity = stock_quantity + ? 
  WHERE ?",
    [
      {
        addQty
      },
      {
        item_id: itemID
      }
    ],
    function(err, result) {
      if(err) {
        console.log(err);
      }

      console.log(result);

      console.log("Stock Quantity of item " + itemID + " increased by " + 
      addQty + " units.");
    }
  );
}

【问题讨论】:

  • 你得到的错误是什么?

标签: javascript mysql node.js


【解决方案1】:

您可以将加法连接到 SQL 字符串(尽管我从不建议使用 over 参数,但在这里您可以控制值):

connection.query("UPDATE product SET stock_quantity = stock_quantity + " + addQTY + " WHERE ?",
    [
      {
        item_id: itemID
      }
    ],
    ...

或者如果您总是通过item_id 进行检查,您可以参数化查询:

connection.query("UPDATE product SET stock_quantity = stock_quantity + 
  ? WHERE item_id = ?",
    [ addQty, itemID ],
    ...

【讨论】:

    猜你喜欢
    • 2012-10-31
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 2020-09-24
    • 1970-01-01
    • 2021-03-10
    相关资源
    最近更新 更多