Search code examples
mysqlinsertlastinsertid

What could cause duplicate ids on a auto increment primary key field (mysql)?


RESOLVED

From the developer: the problem was that a previous version of the code was still writing to the table which used manual ids instead of the auto increment. Note to self: always check for other possible locations where the table is written to.

We are getting duplicate keys in a table. They are not inserted at the same time (6 hours apart).

Table structure:

CREATE TABLE `table_1` (
  `sales_id` int(10) unsigned NOT NULL auto_increment,
  `sales_revisions_id` int(10) unsigned NOT NULL default '0',
  `sales_name` varchar(50) default NULL,
  `recycle_id` int(10) unsigned default NULL,
  PRIMARY KEY  (`sales_id`),
  KEY `sales_revisions_id` (`sales_revisions_id`),
  KEY `sales_id` (`sales_id`),
  KEY `recycle_id` (`recycle_id`)
) ENGINE= MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=26759 ;

The insert:

insert into `table_1` ( `sales_name` ) VALUES ( "Blah Blah" )

We are running MySQL 5.0.20 with PHP5 and using mysql_insert_id() to retrieve the insert id immediately after the insert query.


Solution

  • I have had a few duplicate key error suddenly appear in MySql databases in the past even though the primary key is defined and auto_increment. Each and every time it has been because the table has become corrupted.

    If it is corrupt performing a check tables should expose the problem. You can do this by running:

    CHECK TABLE tbl_name
    

    If it comes back as corrupt in anyway (Will usually say the size is bigger than it actually should be) then just run the following to repair it:

    REPAIR TABLE tbl_name