25

I have a table (name, date, stat1, stat2, stat3), (name, date) is the PK. When I insert rows, there will be duplicate keys, and I need to sum up the three stats. I use the following query with PreparedStatement in Java:

INSERT INTO tb (name, date, stat1, stat2, stat3)
VALUES (?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE stat1 = stat1 + ?, stat2 = stat2 + ?, stat3 = stat3 + ?

Is there a more concise query to achieve that? Because I have simplify the query, there are over ten stats there.

3 Answers 3

47
INSERT INTO tb (name, date, stat1, stat2, stat3)
VALUES (?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE stat1 = stat1 + VALUES(stat1), stat2 = stat2 + VALUES(stat2), stat3 = stat3 + VALUES(stat3)
Sign up to request clarification or add additional context in comments.

2 Comments

It is better. But is it possible that I don't need to repeat every stat?
I see this is an old question, but another option is writing a procedure with the stats in a string and then looping through them (after splitting). May not be less code but it will be more dynamic.
0

Add a computed column (sum) and include that in your PK.

However, this does denormalize your table. You could use a surrogate key and do the calculation in your SELECT

Comments

-3

If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, MySQL performs an UPDATE of the old row. For example, if column a is declared as UNIQUE and contains the value 1, the following two statements have similar effect:

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

The equivalent update query is as below,

UPDATE table SET c=c+1 WHERE a=1;

If a and b column is unique, equivalent update query would be ,

UPDATE table SET c=c+1 WHERE a=1 OR b=2 LIMIT 1;

1 Comment

You've already posted the same answer here. If you feel this question is similar, flag it as a duplicate instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.