Page is a not externally linkable
- Code, Content, and Presentation
-- Databases
---- Conditional mysql insert question - how to prevent duplicates


brotherhood_of_LAN - 10:09 pm on Aug 3, 2011 (gmt 0)


Is there a PRIMARY or UNIQUE key on the table already?

If not,

ALTER IGNORE TABLE `tablename` ADD PRIMARY KEY (`term`,`url` ) ;


This will add the key and also remove any duplicates.

INSERT IGNORE tablename (term,url) VALUES ('$term','$url') ON DUPLICATE KEY UPDATE countercolumn = countercolumn + 1


This will increment counter column by one if the term/url combo already exists. It relies on the primary/unique index and reverts to updating when the value already exists.

[dev.mysql.com...]

In general, you should try to avoid using an ON DUPLICATE KEY clause on tables with multiple unique indexes.


Thread source:: http://www.webmasterworld.com/databases_sql_mysql/4347419.htm
Brought to you by WebmasterWorld: http://www.webmasterworld.com