Reputation: 32221
I have two tables (bold=PK):
log: [id,type, value]
totals: [type,total]
Where the "total" value at "totals" is the sum of the values of all entries in the log with the same type. I want to update the totals table so I run a query:
INSERT INTO totals (type,total) (SELECT type,sum(value) AS total FROM log GROUP BY type)
This works fine except when the PK already exists, I'm trying to solve it adding a:
ON DUPLICATE KEY UPDATE total=XXXXXXXX
but I don't know what to put as XXXXXXXXX to refer the new value
Upvotes: 3
Views: 1704
Reputation: 613
As Gordon already said, you use VALUES(field
) to get the value that would be inserted, or just field
to get the old value
INSERT INTO .... ON DUPLICATE KEY UPDATE `field` = VALUES(`field`)
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
In your case - the complete query should look something like:
INSERT INTO totals (type,total) (SELECT type,sum(value) AS total FROM log GROUP BY type) ON DUPLICATE KEY UPDATE total = VALUES(total)
Upvotes: 2
Reputation: 3234
I'm not sure if I understand what do you want but:
ON DUPLICATE KEY UPDATE total = (SELECT COUNT(*) FROM log l WHERE l.type = type)
Upvotes: 1