0

我正在尝试使用 WHERE 子句从 Node.js 将多条记录插入 MYSQL,但我不断收到语法错误。

在我尝试向其添加条件语句之前,该语句工作正常。然后我得到这个错误: ER_PARSE_ERROR: 你的 SQL 语法在 VALUES 附近有错误吗?在哪里 ...

var Data = data; // this is a nested array already as received from client side like [[..],[..],[..]]
var ID = 123; 

 var sql = "INSERT INTO table1 (Col1,Col2,Col3,Col4,Col5) VALUES ? WHERE"+ID+" NOT IN (SELECT somecol FROM table2 WHERE somecol= "+ID+")"

connection.query(sql, [Data], function (error, result) {
    if (error) {
        throw error;
        res.json({ Message: "Oops something went wrong :("});
    }

    res.json({ Message: "Your data was added!"});
});

该连接已设置为允许多个语句:

var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '1234',
    database: 'thedb',
    port: 12345,
    charset: "utf8mb4",
    multipleStatements: true
});

查询在没有 WHERE 子句的情况下以这种形式工作:

var Data = data; // this is a nested array already as received from client side like [[..],[..],[..]]
var ID = 123; 

var sql = "INSERT INTO table1 (Col1,Col2,Col3,Col4,Col5) VALUES ?"

connection.query(sql, [Data], function (error, result) {
    if (error) {
        throw error;
        res.json({ Message: "Oops something went wrong :("});
    }

    res.json({ Message: "Your data was added!"});
});

如何使查询与 WHERE 子句一起使用?

4

1 回答 1

0

Insert命令不适用于Where子句,因为您要插入新行。简单来说,一个Where子句需要根据条件过滤掉一些行。根据您的用例,您可以有两种可能的解决方案:

  1. 使用Update可能类似于的语句 Update table set col1=val1 where (condition clause)

  2. 如果您真的想使用Where子句,那么您可以使用Insert以下形式的命令

Insert into table(col1,col2) Select (val1, val2) from table2 where (condition clause);

于 2018-11-25T14:31:20.933 回答