Wednesday, October 8, 2008

ON DUPLICATE KEY UPDATE

INSERT ON DUPLICATE KEY UPDATE - MySQL Performance Blog
http://www.mysqlperformanceblog.com/2006/05/29/insert-on-duplicate-key-update-and-summary-counters/

example:
      CREATE TABLE ipstat(ip int UNSIGNED NOT NULL PRIMARY KEY,
                                hits int UNSIGNED NOT NULL,
                                last_hit timestamp);
      INSERT INTO ipstat VALUES(inet_aton('192.168.0.1'),1,now())
                             ON duplicate KEY UPDATE hits=hits+1;
info: If there is no such IP address in the table it will be added with hits=1 if it is already where (note ip is PRIMARY KEY) it would be just incremented and last visit timestamp updated.

performance boost: 30% speedup should be typical.

more: This example actually shows one more neat feature of MySQL - inet_aton  and inet_ntoa functions which can convert IP address strings to integers and back. This allows to save on field length significantly by using 4 bytes instead of 15

INSERT ON DUPLICATE Syntax
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

No comments: