首页 > 解决方案 > SQL 选择和更新语法

问题描述

我正在尝试使用单个语句在 SQL 中执行 SELECT 和 UPDATE。在一些 Google FU 之后,我似乎找不到任何文档。或者,也许我正在寻找错误的东西。

inquirer
        .prompt([{
            name: "updateID",
            type: "input",
            message: "What's the ID of the product you'd like to update?"
        },
        {
            name: "updateQuantity",
            type: "input",
            message: "How many units would you like to add to inventory?"
        }]).then(function(answer) {
            connection.query("SELECT id, stock_quantity FROM products WHERE ?", 
            {
                id: parseInt(answer.updateID)
            }, function(err, res) {

            })

        })

我希望有一种方法可以在单个语句中执行 SELECT 和 UPDATE。

标签: javascriptmysqlsqlnode.js

解决方案


除非您特别想读取该产品的数据,否则您不需要SELECT在值之前执行 a UPDATE。根据您的代码,此查询应该执行您想要的操作:

UPDATE products
SET stock_quantity = stock_quantity + ?
WHERE id = ?

如果您还想读取数据,则必须执行单独SELECTUPDATE查询。


推荐阅读