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

4

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

  

# 1062 - Duplicate entry for key 'PRIMARY'

The data is populated and looks something like this:

I tried to put Sub_Id as the primary key.

    
asked by anonymous 27.04.2015 / 16:01

2 answers

3

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

It seems to me that your table has a key composed of area_id and sub_id . Try setting the both columns as the primary key:

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

Alternatively, you can create a new column to be the primary key ( Surrogate Key ):

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

More information about ALTER TABLE in the MySQL documentation .     

28.05.2015 / 19:38
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

    
07.10.2016 / 09:41