Tuesday, January 17, 2017

[mysql][resolved] Error Code: 1062. Duplicate entry '0' for key

Related SQL which cause the error :
INSERT INTO `tags` (`tag_name`, `create_date`, `create_by`, `last_update_date`, `update_by`) VALUES ('job', '2017-01-20 12:37:17', '2', '2017-01-20 12:37:17', '2')
Error msg :
Error Code: 1062. Duplicate entry '0' for key 1    0.000 sec


You have to check out if your have specify the primary key as auto-increment .

=========

1) Check table structure

Use the command to  "SHOW CREATE TABLE" to check the table structure, change the text in orange background to your table name:
SHOW CREATE TABLE tags
Result :
 'CREATE TABLE `tags` (
  `tag_id` int(11) NOT NULL,
  `tag_name` varchar(45) default NULL,
  `create_date` timestamp NULL default NULL,
  `create_by` varchar(45) default NULL,
  `last_update_date` timestamp NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
  `update_by` varchar(45) default NULL,
  PRIMARY KEY  (`tag_id`)
) ENGINE=MyISAM AUTO_INCREMENT=110 DEFAULT CHARSET=utf8'
For my case the primary key  (`tag_id`) haven't set as auto_increment , go alter the table and set your primary key as auto_increment. (Change the text in yellow background to fit your case)
ALTER TABLE tags CHANGE tag_id tag_id INT(11) AUTO_INCREMENT;
Reference:
http://stackoverflow.com/questions/28430941/error-1062-duplicate-entry-0-for-key-primary-when-adding-a-primary-key

No comments :

Post a Comment