Question

I have a table with four columns, (id, searchstring, count, timestamp).
I want to be able to make to use of the ON DUPLICATE KEY UPDATE feature to update the count of searchstring when a duplicate is entered.

However, searchstring needs to be the primary key to be able to do this, and my id is automatically set to my primary key because it is auto incrementing.
Is there any way around this?

Was it helpful?

Solution

Yes, set the primary key to include both id and searchstring

CREATE TABLE  `test`.`new table` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `searchstring` varchar(45) NOT NULL,
  `count` int(10) unsigned NOT NULL,
  `timest` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`,`searchstring`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

You can change the existing table using:

ALTER TABLE `test`.`new table` DROP PRIMARY KEY,
 ADD PRIMARY KEY  USING BTREE(`id`)
 ADD UNIQUE INDEX ss(searchstring);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top