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 th
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)
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;
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