ON DUPLICATE KEY UPDATE - add to existing value

后端 未结 1 1041
伪装坚强ぢ
伪装坚强ぢ 2020-12-20 22:52

I have SQL (MySQL 5.x) query like:

           INSERT INTO table (val1),
           ON DUPLICATE KEY UPDATE `val1` = VALUES(`val1`)

And this

相关标签:
1条回答
  • 2020-12-20 23:20

    Right at the top of the fine manual you will see an example of exactly the sort of thing you're trying to do:

    INSERT INTO table (a,b,c) VALUES (1,2,3)
      ON DUPLICATE KEY UPDATE c=c+1;
    

    So you're looking for this:

    connection.execute(%Q{
        INSERT INTO table (val1) VALUES(#{connection.quote(x)})
        ON DUPLICATE KEY UPDATE `val1` = `val1` + #{connection.quote(ruby_variable)}
    })
    

    Where x is what you're trying to insert and ruby_variable is what you want to add to val1 when there is a duplicate. You need a VALUES for the INSERT, not for the ON DUPLICATE.

    0 讨论(0)
提交回复
热议问题