Part of the system I'm working on at the moment involves a log in mysql, with counts being frequently updated.
The data being inserted is of the format:
date | name | count |
-----------+------+-------+
2009-01-12 | alan | 5 |
2009-01-12 | dave | 2 |
2009-01-12 | mary | 1 |
This data is parsed regularly from a flat file, summarised as above in preparation for a db insert/update - the unique key on the database is the (date, name)
pair.
Previously, this system would check the existing table for any records for a given date
and name
pair before deciding on an update or insert.
The problem we're having is, as this table grows, the response time isn't getting any better, and we want to reduce the number of queries as much as possible.
The system was recently updated to run a INSERT ... ON DUPLICATE KEY UPDATE
query, which has reduced the number of select
s marginally, but our common case by some distance is the update
.
I'm wondering if anyone knows of a mysql function that's essentially INSERT ... ON DUPLICATE KEY UPDATE
in reverse, i.e. will try to update a row, if none match then perform the insert?
Edit
I didn't make it too clear above, what I would like to do when I have the record ('2009-01-12','alan','5')
for example, is:
UPDATE table SET count = count+5 WHERE date = '2009-01-12' and name = 'alan';
and if the above fails, insert the above data. The need to increment a counter is why REPLACE
won't work. Replace performs a delete & insert, and doesn't let you refer to the row being deleted, so count = count + 5
wouldn't increment the previous count
value for by 5.
@jasoncohen - the INSERT ... ON DUPLICATE KEY UPDATE
does do the job, but I'm asking if there's a more optimal way to do this.
Sorry for any confusion resulting from the poor original phrasing!