I am trying to insert multiple records into MYSQL from Node.js with a WHERE clause but I keep getting a syntax error.
The statement works fine until I try to add a conditional statement to it. Then I get this error: ER_PARSE_ERROR: You have an error in your SQL syntax near VALUES ? 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 ? 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!"});
});
The connection is set up to allow multiple statements already:
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '1234',
database: 'thedb',
port: 12345,
charset: "utf8mb4",
multipleStatements: true
});
The query works in this form without the WHERE clause:
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!"});
});
How do I get the query work with the WHERE clause?
Insertcommand will not work withWhereclause because you are inserting a new row. In naive terms, aWhereclause needs some rows to filter out based on the conditions. Based on your use case you can have two possible solutions:Use
Updatestatements which could be likeUpdate table set col1=val1 where (condition clause)If you really want to use
Whereclause then you can use theInsertcommand in the following formInsert into table(col1,col2) Select (val1, val2) from table2 where (condition clause);