I'm using NodeJS with MySQL and async/await statements. I've got a UNIQUE column in a MySQL table named audioid
.
I need to check if an audioid exists. If so I need to update a row. If not I need to insert a row. I'm using MySQL's So here's the query;
try {
if(tag1){
row_b = await db.query( "SELECT tagid FROM tags WHERE tagname = ?", [tag1]);
if (row_b > 0){
const tagid1 = row_b[0].tagid;
console.log('tagid first = ' + tagid1);
row_c = await db.query(
"INSERT INTO entitytag (tagid1) VALUES (?) WHERE audioid = ?
ON DUPLICATE KEY UPDATE tagid1 = ?", [tagid1, audioid, tagid1]
);
}
else {
row_d = await db.query( 'INSERT IGNORE INTO tags (tagname) VALUES (?)', [tag1]);
const tagid1 = row_d.insertId;
console.log('tagid 2nd = ' + tagid1);
row_e = await db.query(
"INSERT INTO entitytag (tagid1) VALUES (?) WHERE audioid = ?
ON DUPLICATE KEY UPDATE tagid1 = ?", [tagid1, audioid, tagid1]
);
}
console.log('success!');
res.json('success!');
}
}
But there's the error in the console;
[ RowDataPacket { tagid: 11 } ] tagid 2nd = 0 ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE audioid = 26 ON DUPLICATE KEY UPDATE tagid1 = 0' at line 1
INSERT INTO entitytag (tagid1) VALUES (?) WHERE audioid = ?
ON DUPLICATE KEY UPDATE tagid1 = ?
is wrong on a SQL basis since insert creates a new row, so there are no WHERE conditions applicable. If you want to specify that the duplicate check should happen on audioid then you should create an index on the table with UNIQUE attribute on that field.
The correct query (from an syntax standpoint only) is
INSERT INTO entitytag (tagid1) VALUES (?)
ON DUPLICATE KEY UPDATE tagid1 = ?
Without having sample data,expected results and table structures it is a matter of guessing but a working (functionally) query could be:
INSERT INTO entitytag (tagid1, audioid) VALUES (?,?)
ON DUPLICATE KEY UPDATE tagid1 = ?