Im running a database log and every day I log on a new row. My Mysql query therefore checks if the day (date (the unique key)) already exists, and if so, it tries to increment all the loggable values of the log-row by one. If the date record doesnt eyist yet, it will create a new row.
My SQL query is:
INSERT INTO `log` (`date`,`hits`,`stale`)
VALUES ('2012-03-06',1,1)
ON DUPLICATE KEY
UPDATE `hits`=`hits`+1,`stale`=`stale`+1
WHERE `date`='2012-03-06';"
All columns have 0 as default value, so if this query runs directly after midnight only 'stale' and 'hits' are set to 1. Otherwise 'stale' and 'hits' are both incremented.
I wish! (it doesn't work).
What am I missing? Which separator other then a comma should I use between 'hits' = 'hits' +1 and 'stale'='stale'+1?
Your separator is correct, but the UPDATE has already found the duplicate row to be able to trigger the ON DUPLICATE KEY, so you don't need to try to select it again using WHERE.
Demo here.
Just get rid of the WHERE clause:
If you only want to do the update if some specific expression is true, you can do it with two statements:
The
INSERT
will silently fail if there is a duplicate key.You shouldn't have the
WHERE
clause.ON DUPLICATE KEY UPDATE
automatically limits the row it affects to the one that has the existing key.Remove it and your query should work fine.