'Use ON DUPLICATE KEY to increment columns by a set amount MySQL NodeJS
I need to use ON DUPLICATE KEY to increment columns in my table by a set amount. How would I go about getting the current value of the column and incrementing it by X amount.
Note: I'm using the nodejs mysql package and this is my code currently:
db.query(`INSERT INTO some_table SET ? ON DUPLICATE KEY UPDATE ?`, [
{
sessions: 25,
pageviews: 240
},
{
sessions: `sessions + ${sessionsIncrementAmount}`,
pageviews: `pageviews + ${pageviewsIncrementAmount}`
}
])
Solution 1:[1]
You can't use placehoders, but you can use the variables in the string in combination with the sql syntax column_name = column_name + yournumber
db.query(`INSERT INTO some_table SET ? ON DUPLICATE KEY UPDATE sessions = sessions + ${sessionsIncrementAmount},pageviews = pageviews + ${sessionsIncrementAmount}`, [
{
sessions: 25,
pageviews: 240
}
])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
