Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

mysql - ON DUPLICATE KEY UPDATE - add to existing value

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

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

And this works fine.

Now i need to update it with a sum of VALUES(val1) + ruby variable.

           INSERT INTO table (val1),
           ON DUPLICATE KEY UPDATE `val1` = VALUES(`val1`) + #{ruby_variable}

throws me an error.

(Ruby here is just an example, actually i need to sum VALUES(val1) + integer)

How it could be done?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...