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
ON DUPLICATE KEY UPDATEqueries. based on your example code it looks like your goal is to maintain key values across related tables. you might also consider leveraging foreign keys and referential actions, tablet riggers, stored procedures, or any combination of those options. They might save you some time and resources depending on your architecture and throughput for this specific case.