Use UPDATE
, not REPLACE
. REPLACE
is used when you need to either update or insert depending on whether the row already exists. But since you're joining the tables, the row already has to exist, so there's no need for the insert option.
db.query('UPDATE table2 AS t2
JOIN table1 AS t1 ON t1.a = t2.a AND t1.b = t2.b
SET t2.c = ?
WHERE t1.id = ?',
[c, id]);
If you do need to handle the case where the row doesn't already exist, use INSERT
with the ON DUPLICATE KEY UPDATE
option.
db.query('INSERT INTO table2 (a, b, c)
SELECT a, b, ?
FROM table1 WHERE id = ?
ON DUPLICATE KEY c = VALUES(c)',
[c, id]);
Make sure there's a unique key on (a, b)
in table2
. If there isn't, add one:
ALTER TABLE table2 ADD UNIQUE KEY (a, b);
Here's another way to do it. You can use the UPDATE
query at the top for the rows that have matches between the two tables, and the following INSERT
query to add rows that don't have a match:
db.query('INSERT INTO table2 (a, b, c)
SELECT t1.a, t1.b, ?
FROM table1 AS t1
LEFT JOIN table2 AS t2 ON t1.a = t2.a AND t1.b = t2.b AND t1.id = ?
WHERE t2.a IS NULL",
[c, id]);
The SELECT
query it uses is based on Return row only if value doesn't exist.