Ethan Crabb
Ethan Crabb

Reputation: 373

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

Upvotes: 2

Views: 132

Answers (1)

nbk
nbk

Reputation: 49395

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

Upvotes: 2

Related Questions