MySQL: Duplicate Entry for Key 2

28,585

Solution 1

You have vid as a unique key. However you never set a value for it so the default 0 is always used. Second entry into the table will violate uniqueness.

Solution 2

The problem looks to be with vid not being specified. The first entry you put will have had a vid of 0 (the default) and the next will try 0 again and fail on the UNIQUE index. Not that only the primary key, nid, will auto-increment.

Share:
28,585
Nick Heiner
Author by

Nick Heiner

JS enthusiast by day, horse mask enthusiast by night. Talks I've Done

Updated on August 05, 2022

Comments

  • Nick Heiner
    Nick Heiner almost 2 years

    I'm not sure what I'm doing to cause this error. The query:

    INSERT INTO node (type, language, title) VALUES ('bout', 'en', 'the title 3')
    

    The error:

    #1062 - Duplicate entry '0' for key 2 
    

    The table:

    CREATE TABLE `node` (
      `nid` int(10) unsigned NOT NULL auto_increment,
      `vid` int(10) unsigned NOT NULL default '0',
      `type` varchar(32) NOT NULL default '',
      `language` varchar(12) NOT NULL default '',
      `title` varchar(255) NOT NULL default '',
      `uid` int(11) NOT NULL default '0',
      `status` int(11) NOT NULL default '1',
      `created` int(11) NOT NULL default '0',
      `changed` int(11) NOT NULL default '0',
      `comment` int(11) NOT NULL default '0',
      `promote` int(11) NOT NULL default '0',
      `moderate` int(11) NOT NULL default '0',
      `sticky` int(11) NOT NULL default '0',
      `tnid` int(10) unsigned NOT NULL default '0',
      `translate` int(11) NOT NULL default '0',
      PRIMARY KEY  (`nid`),
      UNIQUE KEY `vid` (`vid`),
      KEY `node_changed` (`changed`),
      KEY `node_created` (`created`),
      KEY `node_moderate` (`moderate`),
      KEY `node_promote_status` (`promote`,`status`),
      KEY `node_status_type` (`status`,`type`,`nid`),
      KEY `node_title_type` (`title`,`type`(4)),
      KEY `node_type` (`type`(4)),
      KEY `uid` (`uid`),
      KEY `tnid` (`tnid`),
      KEY `translate` (`translate`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2586 ;
    

    What am I doing wrong? By not specifying a nid for the new entry, it will auto-increment, right?