Home > Software design >  Use ON DUPLICATE KEY to increment columns by a set amount MySQL NodeJS
Use ON DUPLICATE KEY to increment columns by a set amount MySQL NodeJS

Time:04-11

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}`
    }
])

CodePudding user response:

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
    }
])
  • Related