Error #1062 - Duplicate entry '1' for key 'PRIMARY'

Asked

Viewed 17,275 times

8

I was trying to put one of my tables as primary key. As soon as I try to get the message:

#1062 - Duplicate entry for key 'PRIMARY'

The data are filled in and are more or less like this:

Dados

I tried to put as the primary key Sub_Id.

  • Were you unable to include a record or were you unable to set SUB_ID as the primary key? I think your question can be "improved" is a little confusing... it seems that you are getting error by trying to insert a record with a SUB_ID that already exists and if it is Primary key, really, can not.

  • I couldn’t put SUB_ID as the primary key.

  • What action are you executing when you get this error? You are changing the table or making an Insert?

  • I’m trying to put Sub_id as the primary key. That’s when I get the bug.

  • the data is already filled but I want to change and I have the message : This table does not contain a Unique column. Grid Edit, checkbox, Edit, Copy and Delete Features are not available.

  • I had this problem with my vBulletin, and changed the engine from innodb to myisam and was solved...

  • The guy is already as Myisam and does not work the same

  • If you put any other data as a primary key there is a problem?

  • make a select and see if you have someone who repeats the sub_id... if you repeat it it will not even accept.

  • Tip: You can select only the id_area and sub_id fields of the table: SELECT id_area, sub_id FROM tabela, instead of *

Show 5 more comments

3 answers

5

As reported by the error message, the field sub_id is not unique and repeats itself.

It seems to me that your table has a composite key between area_id and sub_id. Try to define both columns as primary key:

ALTER TABLE tabela
ADD CONSTRAINT pk_AreaId_SubId PRIMARY KEY (area_id,sub_id);

You can also create a new column to be the primary key for this combination of area_id and sub_id (this is called surrogate key):

ALTER TABLE tabela
ADD id_pk INT NOT NULL PRIMARY KEY AUTO_INCREMENT FIRST;

More information on the ALTER TABLE in mysql documentation.

0

Do the following query and see the cause of the problem:

SELECT SUB_ID, COUNT(*) TOTAL FROM TABELA GROUP BY SUB_ID HAVING COUNT(*) > 1

0

In the sub_id, the field cannot be set to 0, if not the DB gets lost in the count. Switch to any other value that DB returns to normal.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.