MYSQL和Node.js具有where子句的多条记录插入

时间:2018-11-25 13:17:34

标签: mysql node.js multiple-insert

我正在尝试使用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子句一起使用?

1 个答案:

答案 0 :(得分: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);