I'm using MySQL for the first time through a NodeJS application. I'm managing to insert into a table, but I'm attempting to adapt my code to upsert the data instead, if a value matches. I've been trying to incorporate "ON DUPLICATE KEY UPDATE", but instead my data is getting inserted twice.
Within the NodeJS application, the mysql version is 2.18.1
My data is structured in an array of objects, like below:
const data = [
{staffId: 12345, name : "John Doe", age: 40},
{staffId: 67890, name : "Michael Jordan", age: 45},
{staffId: 33333, name : "Jane Doe", age: 50},
]
Below is the code I've been using for a plain old insert, which is working as intended:
const connection = await mysql.createConnection({
host: "xxxxx",
user: "xxxxx",
password: "xxxxx",
database: "xxxxxx",
multipleStatements: true,
});
let query = "";
data.forEach((item) => {
query += mysql.format("REPLACE INTO staff_data SET ?", item);
query += ";"
});
await connection.query(query);
How can I adapt this so that if a duplicate staffId
is passed, the row is updated rather than creating a new table row?
I have tried adding in the below line, into the loop (after the initial mysql.format method):
query += mysql.format(" ON DUPLICATE KEY UPDATE ?", {staffId: item.staffId})
Any help would be great. MySQL is confusing coming from a background of MongoDB!
Thanks
edit: I've tried updating an age using the below query but I get a syntax error. I also tried using the INSERT
keyword instead of replace.
REPLACE INTO staff_data VALUES `staffId` = 12345, `name` = ‘John Doe’, `age` = ‘60’, ON DUPLICATE KEY UPDATE staffId = VALUES(‘staffId’);
ON DUPLICATE KEY UPDATE staffid = NEW.staffid
(or before MySQL 8,staffid = VALUES(staffid)
)${item.staffId}
, juststaffid
.VALUES(columnname)
means to use the value that would have been inserted it not for the duplicate.staffId
= 12345,name
= ‘John Doe’,age
= ‘60’, ON DUPLICATE KEY UPDATE staffId = VALUES(‘staffId’);```REPLACE
doesn't useON DUPLICATE KEY
.