So, my professor gave me tables to insert it in a database but when I execute his code, MySQL is constantly giving the Error Code: 1062.
Here is the conflict tables and the inserts:
TABLES
CREATE TABLE FABRICANTES(
COD_FABRICANTE integer NOT NULL,
NOMBRE VARCHAR(15),
PAIS VARCHAR(15),
primary key (cod_fabricante)
);
CREATE TABLE ARTICULOS(
ARTICULO VARCHAR(20)NOT NULL,
COD_FABRICANTE integer NOT NULL,
PESO integer NOT NULL ,
CATEGORIA VARCHAR(10) NOT NULL,
PRECIO_VENTA integer,
PRECIO_COSTO integer,
EXISTENCIAS integer,
primary key (articulo,cod_fabricante),
foreign key (cod_fabricante) references Fabricantes(cod_fabricante)
);
INSERT INTO:
INSERT INTO FABRICANTES VALUES(10,'CALVO', 'ESPAÑA');
INSERT INTO FABRICANTES VALUES(15,'LU', 'BELGICA');
INSERT INTO FABRICANTES VALUES(20,'BARILLA', 'ITALIA');
INSERT INTO FABRICANTES VALUES(25,'GALLO', 'ESPAÑA');
INSERT INTO FABRICANTES VALUES(30,'PRESIDENT', 'FRANCIA');
INSERT INTO ARTICULOS VALUES ('Macarrones',20, 1, 'Primera',100,98,120);
INSERT INTO ARTICULOS VALUES ('Tallarines',20, 2, 'Primera',120,100,100);
INSERT INTO ARTICULOS VALUES ('Tallarines',20, 1, 'Segunda',99,50,100);
INSERT INTO ARTICULOS VALUES ('Macarrones',20, 1, 'Tercera',80,50,100);
INSERT INTO ARTICULOS VALUES ('Atún',10, 3, 'Primera',200,150,220);
INSERT INTO ARTICULOS VALUES ('Atún',10, 3, 'Segunda',150,100,220);
INSERT INTO ARTICULOS VALUES ('Atún',10, 3, 'Tercera',100,50,220);
INSERT INTO ARTICULOS VALUES ('Sardinillas',10, 1,'Primera',250,200,200);
INSERT INTO ARTICULOS VALUES ('Sardinillas',10, 1,'Segunda',200,160,200);
INSERT INTO ARTICULOS VALUES ('Sardinillas',10, 1,'Tercera',100,150,220);
INSERT INTO ARTICULOS VALUES ('Mejillones',10, 1, 'Tercera',90,50,200);
INSERT INTO ARTICULOS VALUES ('Mejillones',10, 1, 'Primera',200,150,300);
INSERT INTO ARTICULOS VALUES ('Macarrones',25, 1, 'Primera',90,68,150);
INSERT INTO ARTICULOS VALUES ('Tallarines',25, 1, 'Primera',100,90,100);
INSERT INTO ARTICULOS VALUES ('Fideos',25, 1, 'Segunda',75,50,100);
INSERT INTO ARTICULOS VALUES ('Fideos',25, 1, 'Primera',100,80,100);
INSERT INTO ARTICULOS VALUES ('Galletas Cuadradas',15, 1, 'Primera',100,80,100);
INSERT INTO ARTICULOS VALUES ('Galletas Cuadradas',15, 1, 'Segunda',70,50,100);
INSERT INTO ARTICULOS VALUES ('Galletas Cuadradas',15, 1, 'Tercera',50,40,100);
INSERT INTO ARTICULOS VALUES ('Barquillos',15, 1, 'Primera',100,80,100);
INSERT INTO ARTICULOS VALUES ('Barquillos',15, 1, 'Segunda',100,80,100);
INSERT INTO ARTICULOS VALUES ('Canutillos',15, 2, 'Primera',170,150,110);
INSERT INTO ARTICULOS VALUES ('Canutillos',15, 2, 'Segunda',120,150,110);
INSERT INTO ARTICULOS VALUES ('Leche entera',30, 1, 'Primera',110,100,300);
INSERT INTO ARTICULOS VALUES ('Leche desnat.',30, 1, 'Primera',120,100,300);
INSERT INTO ARTICULOS VALUES ('Leche semi.',30, 1, 'Primera',130,110,300);
INSERT INTO ARTICULOS VALUES ('Leche entera',30, 2, 'Primera',210,200,300);
INSERT INTO ARTICULOS VALUES ('Leche desnat.',30, 2, 'Primera',220,200,300);
INSERT INTO ARTICULOS VALUES ('Leche semi.',30, 2, 'Primera',230,210,300);
INSERT INTO ARTICULOS VALUES ('Mantequilla',30, 1, 'Primera',510,400,200);
INSERT INTO ARTICULOS VALUES ('Mantequilla',30, 1, 'Segunda',450,340,200);
The ERROR:
Error Code: 1062. Duplicate entry 'Macarrones-20' for key 'PRIMARY'
If I delete that row gives me the same error but with ‘Tallarines-20’
Sorry if there is any spell mistake. Thanks!
Here at Bobcares, we provide Server Administration and Maintenance services to website owners and web solution providers.
An error we sometimes see in MySQL servers while updating, restoring or replicating databases is: “Error No: 1062” or “Error Code: 1062” or “ERROR 1062 (23000)“
A full error log that we recently saw in a MySQL cluster is:
could not execute Write_rows event on table mydatabasename.atable; Duplicate entry ’174465′ for key ‘PRIMARY’, Error_code: 1062; handler error HA_ERR_FOUND_DUPP_KEY; the event’s master log mysql-bin.000004, end_log_pos 60121977
What is MySQL Error No: 1062?
Simply put, error 1062 is displayed when MySQL finds a DUPLICATE of a row you are trying to insert.
We’ve seen primarily 4 reasons for this error:
- The web application has a bug that adds primary key by large increments, and exhausts the field limit.
- MySQL cluster replication tries to re-insert a field.
- A database dump file contains duplicate rows because of coding error.
- MySQL index table has duplicate rows.
In rare cases, this error is shown when the table becomes too big, but let’s not worry about that for now.
How to fix Error No 1062 when your web appilcation is broken
Every database driven application like WordPress, Drupal or OpenCart distinguishes one user or data set from another using something called a “primary field”.
This primary field should be unique for each user, post, etc.
Web apps use a code like this to insert data:
INSERT INTO table ('id','field1','field2','field3') VALUES ('NULL','data1','data2','data3');
Where “id” is the unique primar key, and is set to auto-increment (that is a number inserted will always be greater than the previous one so as to avoid duplicates).
This will work right if the value inserted is “NULL” and database table is set to “auto-increment”.
Some web apps make the mistake of passing the value as
VALUES ('','data1','data2','data3');
where the first field is omitted. This will insert random numbers into the primary field, rapidly increasing the number to the maximum field limit (usually 2147483647 for numbers).
All subsequent queries will again try to over-write the field with “2147483647”, which MySQL interprets as a Duplicate.
Web app error solution
When we see a possible web application code error, the developers at our Website Support Services create a patch to the app file that fixes the database query.
Now, we have the non-sequential primary key table to be fixed.
For that, we create a new column (aka field), set it as auto-increment, and then make it the primary key.
The code looks approximately like this:
alter table table1 drop primary key;
alter table table1 add field2 int not null auto_increment primary key;
Once the primary key fields are filled with sequential values, the name of the new field can be changed to the old one, so that all web app queries will remain the same.
Warning : These commands can get very complex, very fast. So, if you are not sure how these commads work, it’s best to get expert assistance.
Click here to talk to our MySQL administrators. We are online 24/7 and can help you within a few minutes.
How to fix MySQL replication Error Code : 1062
Due to quirks in network or synching MySQL is sometimes known to try and write a row when it is already present in the slave.
So, when we see this error in a slave, we try either one of the following depending on many factors such as DB write traffic, time of day etc.
- Delete the row – This is the faster and safer way to continue if you know that the row being written is exactly the same as what’s already present.
- Skip the row – If you are not sure there’d be a data loss, you can try skipping the row.
How to delete the row
First delete the row using the primary key.
delete from table1 where field1 is key1;
Then stop and start the slave:
stop slave;
start slave;
select sleep(5);
Once it is done, check the slave status to see if replication is continuing.
show slave status;
If all is well, you’ll see “Seconds_Behind_Master” as a number. If not, your replication is broken and it needs to be fixed.
How to skip the row
For this, you can set the Skip counter to 1.
Here’s how it could look like:
stop slave;
set global SQL_SLAVE_SKIP_COUNTER = 1;
start slave;
select sleep(5);
Then check the slave status to see if replication is continuing.
show slave status;
Again, if all is well, you’ll see “Seconds_Behind_Master” as a number. If not, your replication is broken and it needs to be fixed.
Proceed with caution
Stopping and starting the slave cannot cause any issue unless you havea very busy database. But, the delete statement, skipping and following up with a broken replication requires expert knowledge about MySQL organization and functioning.
If you are not sure how these commands will affect your database, we recommend you talk to a DB administrator.
Click here to consult our MySQL admins. We are online 24/7 and can attend your request within minutes.
How to fix MySQL restore errors
Restore errors usually take the form of:
ERROR 1062 (23000) at line XXXX: Duplicate entry ‘XXXXXX’ for key X”
When restoring database dumps, this error can happen due to 2 reasons:
- The SQL dump file has dulpicate entries.
- The index file is duplicate rows.
To find out what is exactly going wrong, we look at the conflicting rows and see if they have the same or different data.
If it’s the same data, then the issue could be due to duplicate index rows. If it is different data, the SQL dump file needs to be fixed.
How to fix duplicate entries in database dumps
This situation can happen when two or more tables are dumped into a single file without checking for duplicates.
To resolve this, one way we’ve used is to create a new primary key field with auto-increment and then change the queries to insert NULL value into it.
Then go ahead with the dump.
Once the new primary field table is fully populated, the name of the field is changed to the old primary table name to preserve the old queries.
The alter table command will look like this:
alter table table1 change column 'newprimary' 'oldprimary' varchar(255) not null;
If your index file is corrupted
There’s no easy way to fix an index file if there are duplicate entries in it.
You’ll have to delete the index file, and restore that file either from backups or from another server where your database dump is restored to a fresh DB server.
The steps involved are quite complex to list out here. We recommend that you consult a DB expert if you suspect the index file is corrupted.
Click here to talk to our MySQL administrators. We are online 24/7 and can help you within a few minutes.
Summary
MySQL error no 1062 can occur due to buggy web applications, corrupted dump files or replication issues. Today we’ve seen the various ways in which the cause of this error can be detected, and how it can be resolved.
MAKE YOUR SERVER ROCK SOLID!
Never again lose customers to poor page speed! Let us help you.
Sign up once. Enjoy peace of mind forever!
GET 24/7 EXPERT SERVER MANAGEMENT
var google_conversion_label = «owonCMyG5nEQ0aD71QM»;
I have a problem on this error message, when i try this:
INSERT INTO `PROGETTO`.`UFFICIO-INFORMAZIONI` (`ID`, `viale`, `num_civico`,
`data_apertura`, `data_chiusura`, `orario_apertura`, `orario_chiusura`,
`telefono`, `mail`, `web`, `Nome-paese`, `Comune`)
VALUES (1, 'Viale Cogel ', '120', '2012-05-21', '2012-09-30', '08:00', '23:30',
'461801243', 'informazioni@bolzano.it', 'Bolzanoturismo.it', 'Bolzano', 'BZ')
Error Code: 1062. Duplicate entry ‘1’ for key ‘PRIMARY’
I haven’t auto_increment data, PLEASE HELP me!
This is the table related, UFFICIO-INFORMAZIONI
CREATE TABLE IF NOT EXISTS `PROGETTO`.`UFFICIO-INFORMAZIONI` (
`ID` INT(11) NOT NULL ,
`viale` VARCHAR(45) NULL ,
`num_civico` VARCHAR(5) NULL ,
`data_apertura` DATE NULL ,
`data_chiusura` DATE NULL ,
`orario_apertura` TIME NULL ,
`orario_chiusura` TIME NULL ,
`telefono` VARCHAR(15) NULL ,
`mail` VARCHAR(100) NULL ,
`web` VARCHAR(100) NULL ,
`Nome-paese` VARCHAR(45) NOT NULL ,
`Comune` CHAR(2) NOT NULL ,
PRIMARY KEY (`ID`) ,
INDEX `Nome_paese` (`Nome-paese` ASC) ,
INDEX `Comune` (`Comune` ASC) ,
CONSTRAINT `Nome_paese`
FOREIGN KEY (`Nome-paese` )
REFERENCES `PROGETTO`.`PAESE` (`Nome-paese` )
ON DELETE NO ACTION
ON UPDATE CASCADE,
CONSTRAINT `Comune`
FOREIGN KEY (`Comune` )
REFERENCES `PROGETTO`.`PAESE` (`Comune` )
ON DELETE NO ACTION
ON UPDATE CASCADE)
ENGINE = InnoDB
INSERT INTO
INSERT INTO `PROGETTO`.`UFFICIO-INFORMAZIONI` (`ID`, `viale`, `num_civico`, `data_apertura`, `data_chiusura`, `orario_apertura`, `orario_chiusura`, `telefono`, `mail`, `web`, `Nome-paese`, `Comune`) VALUES (1, 'Viale Cogel ', '120', '2012-05-21', '2012-09-30', '08:00', '23:30', '461801243', 'informazioni@bolzano.it', 'Bolzanoturismo.it', 'Bolzano', 'BZ');
INSERT INTO `PROGETTO`.`UFFICIO-INFORMAZIONI` (`ID`, `viale`, `num_civico`, `data_apertura`, `data_chiusura`, `orario_apertura`, `orario_chiusura`, `telefono`, `mail`, `web`, `Nome-paese`, `Comune`) VALUES (2, 'Via Olmo', '45', '2012-05-01', '2012-09-30', '08:00', '23:30', '393495169301', 'informazioni@lech.it', 'Lechinformation.it', 'Lech', 'BZ');
INSERT INTO `PROGETTO`.`UFFICIO-INFORMAZIONI` (`ID`, `viale`, `num_civico`, `data_apertura`, `data_chiusura`, `orario_apertura`, `orario_chiusura`, `telefono`, `mail`, `web`, `Nome-paese`, `Comune`) VALUES (3, 'Via Quercia', '37', '2012-05-11', '2012-09-30', '08:00', '23:30', '393381679321', 'info@trento.it', 'Trentoinformaiozni.it', 'Trento', 'TN');
INSERT INTO `PROGETTO`.`UFFICIO-INFORMAZIONI` (`ID`, `viale`, `num_civico`, `data_apertura`, `data_chiusura`, `orario_apertura`, `orario_chiusura`, `telefono`, `mail`, `web`, `Nome-paese`, `Comune`) VALUES (4, 'Via Atene', '76', '2012-06-01', '2012-09-15', '08:00', '23:30', '39349361345', 'info@sanmartinodicastrozza.it', 'SanMartino.it', 'San Martino di Castrozza', 'TN');
INSERT INTO `PROGETTO`.`UFFICIO-INFORMAZIONI` (`ID`, `viale`, `num_civico`, `data_apertura`, `data_chiusura`, `orario_apertura`, `orario_chiusura`, `telefono`, `mail`, `web`, `Nome-paese`, `Comune`) VALUES (5, 'Via Salice', '45', '2012-05-01', '2012-09-20', '08:00', '23:30', NULL, 'info@pejo.it', 'Pejoturismo.it', 'Pejo', 'TN');
INSERT INTO `PROGETTO`.`UFFICIO-INFORMAZIONI` (`ID`, `viale`, `num_civico`, `data_apertura`, `data_chiusura`, `orario_apertura`, `orario_chiusura`, `telefono`, `mail`, `web`, `Nome-paese`, `Comune`) VALUES (6, 'Piazza Sempreverde', '34', '2012-05-15', '2012-09-15', '08:00', '23:30', '392516789', 'info@ortisei.it', 'Ortisei.it', 'Ortisei', 'BZ');
ТАБЛИЦЫ
CREATE TABLE FABRICANTES(
COD_FABRICANTE integer NOT NULL,
NOMBRE VARCHAR(15),
PAIS VARCHAR(15),
primary key (cod_fabricante)
);
CREATE TABLE ARTICULOS(
ARTICULO VARCHAR(20)NOT NULL,
COD_FABRICANTE integer NOT NULL,
PESO integer NOT NULL ,
CATEGORIA VARCHAR(10) NOT NULL,
PRECIO_VENTA integer,
PRECIO_COSTO integer,
EXISTENCIAS integer,
primary key (articulo,cod_fabricante),
foreign key (cod_fabricante) references Fabricantes(cod_fabricante)
);
ВСТАВИТЬ В:
INSERT INTO FABRICANTES VALUES(10,'CALVO', 'ESPAÑA');
INSERT INTO FABRICANTES VALUES(15,'LU', 'BELGICA');
INSERT INTO FABRICANTES VALUES(20,'BARILLA', 'ITALIA');
INSERT INTO FABRICANTES VALUES(25,'GALLO', 'ESPAÑA');
INSERT INTO FABRICANTES VALUES(30,'PRESIDENT', 'FRANCIA');
INSERT INTO ARTICULOS VALUES ('Macarrones',20, 1, 'Primera',100,98,120);
INSERT INTO ARTICULOS VALUES ('Tallarines',20, 2, 'Primera',120,100,100);
INSERT INTO ARTICULOS VALUES ('Tallarines',20, 1, 'Segunda',99,50,100);
INSERT INTO ARTICULOS VALUES ('Macarrones',20, 1, 'Tercera',80,50,100);
INSERT INTO ARTICULOS VALUES ('Atún',10, 3, 'Primera',200,150,220);
INSERT INTO ARTICULOS VALUES ('Atún',10, 3, 'Segunda',150,100,220);
INSERT INTO ARTICULOS VALUES ('Atún',10, 3, 'Tercera',100,50,220);
INSERT INTO ARTICULOS VALUES ('Sardinillas',10, 1,'Primera',250,200,200);
INSERT INTO ARTICULOS VALUES ('Sardinillas',10, 1,'Segunda',200,160,200);
INSERT INTO ARTICULOS VALUES ('Sardinillas',10, 1,'Tercera',100,150,220);
INSERT INTO ARTICULOS VALUES ('Mejillones',10, 1, 'Tercera',90,50,200);
INSERT INTO ARTICULOS VALUES ('Mejillones',10, 1, 'Primera',200,150,300);
INSERT INTO ARTICULOS VALUES ('Macarrones',25, 1, 'Primera',90,68,150);
INSERT INTO ARTICULOS VALUES ('Tallarines',25, 1, 'Primera',100,90,100);
INSERT INTO ARTICULOS VALUES ('Fideos',25, 1, 'Segunda',75,50,100);
INSERT INTO ARTICULOS VALUES ('Fideos',25, 1, 'Primera',100,80,100);
INSERT INTO ARTICULOS VALUES ('Galletas Cuadradas',15, 1, 'Primera',100,80,100);
INSERT INTO ARTICULOS VALUES ('Galletas Cuadradas',15, 1, 'Segunda',70,50,100);
INSERT INTO ARTICULOS VALUES ('Galletas Cuadradas',15, 1, 'Tercera',50,40,100);
INSERT INTO ARTICULOS VALUES ('Barquillos',15, 1, 'Primera',100,80,100);
INSERT INTO ARTICULOS VALUES ('Barquillos',15, 1, 'Segunda',100,80,100);
INSERT INTO ARTICULOS VALUES ('Canutillos',15, 2, 'Primera',170,150,110);
INSERT INTO ARTICULOS VALUES ('Canutillos',15, 2, 'Segunda',120,150,110);
INSERT INTO ARTICULOS VALUES ('Leche entera',30, 1, 'Primera',110,100,300);
INSERT INTO ARTICULOS VALUES ('Leche desnat.',30, 1, 'Primera',120,100,300);
INSERT INTO ARTICULOS VALUES ('Leche semi.',30, 1, 'Primera',130,110,300);
INSERT INTO ARTICULOS VALUES ('Leche entera',30, 2, 'Primera',210,200,300);
INSERT INTO ARTICULOS VALUES ('Leche desnat.',30, 2, 'Primera',220,200,300);
INSERT INTO ARTICULOS VALUES ('Leche semi.',30, 2, 'Primera',230,210,300);
INSERT INTO ARTICULOS VALUES ('Mantequilla',30, 1, 'Primera',510,400,200);
INSERT INTO ARTICULOS VALUES ('Mantequilla',30, 1, 'Segunda',450,340,200);
ОШИБКА:
Error Code: 1062. Duplicate entry 'Macarrones-20' for key 'PRIMARY'
Если я удалю эту строку, я получаю ту же ошибку, но с «Tallarines-20»
Извините, если есть ошибка заклинания. Спасибо!
Вы пытаетесь вставить две строки с одним и тем же основным ключом.
INSERT INTO ARTICULOS VALUES ('Tallarines',20, 2, 'Primera',120,100,100);
INSERT INTO ARTICULOS VALUES ('Tallarines',20, 1, 'Segunda',99,50,100);
Вам, вероятно, нужно добавить CATEGORIA
в ваш первичный ключ для таблицы ARTICULOS
, потому что вы пытаетесь вставить несколько строк с одним и тем же основным ключом несколько раз.
primary key (articulo,cod_fabricante, categoria)
Этот код ошибки 1062 происходит из-за дублирования записи. Вы пытаетесь вставить значение, которое уже существует в поле первичного ключа. Недавно я решил эту проблему, добавив auto_increment в поле первичного ключа. Я выполнил исправление, приведенное в этом сообщении как решить код ошибки mysql: 10У меня была такая же ошибка при попытке установить столбец в качестве первичного ключа. Я просто удалил столбец и воссоздал его, что позволило мне назначить его в качестве первичного ключа. Это также устраняет ошибку # 1075, где требуется, чтобы столбец автоматического инкремента был ключом (если вы попытаетесь установить столбец для автоматического увеличения).
7 и 8th INSERT
равны. Вы не можете ввести более одной строки с одним и тем же основным ключом. Обратите внимание, что ваш первичный ключ — это набор: (articulate, cod_fabricante)
, поэтому любая строка с теми же articulate
и cod_fabricante
будет генерировать ошибку 1062.
INSERT INTO ARTICULOS VALUES ('Tallarines',20, 2, 'Primera',120,100,100);
INSERT INTO ARTICULOS VALUES ('Tallarines',20, 1, 'Segunda',99,50,100);
Удалите одну из строк или измените первичный ключ одного из нихУ вас есть ошибка дублирующего ключа во второй таблице ARTICULOS. у вас есть первичный ключ с комбинацией из двух столбцов (articulo, cod_fabricante).
Таким образом, все строки однозначно определяются в комбинации этих столбцов. удалите повторяющиеся строки из второй таблицы или замените первичный ключ.
Это статья является логическим продолжением моего поста Ошибки WordPress при работе с MySql и в ней я расскажу, что делать если в процессе восстановления таблиц MySQL для WordPress вы получили ошибку ERROR 1062: ALTER TABLE causes auto_increment resequencing…
Как исправить ошибку 1062
Не пугайтесь, но для того чтобы исправить ошибку 1062 базы данных MySQL, просто удалите в таблице строку с полем для которого необходимо значение auto_increment. После чего создайте эту строку заново с правильными значениями.
Пример для таблицы wp_term WordPress
Предположим, что у нас неисправна таблица WordPress wp_term. Для исправлении ошибки 1062 воспользуемся утилитой PhpMyAdmin.
Исправная таблица wp_term в WordPress должна выглядеть так:
У меня в неисправной таблице wp_term отсутствовало значение auto_increment для term_id, что приводило к некорректной работе WordPress. В частности было невозможности создать новую Рубрику для записей.
Если при использовании SQL запроса
ALTER TABLE wp_term CHANGE term_id `term_id` bigint(20) unsigned NOT AUTO_INCREMENT;
или редактирования в phpmyadmin
вы получили сообщение об ошибке «ERROR 1062: ALTER TABLE causes auto_increment resequencing..», то удалите это поле (строку) [1]…
… а затем создайте заново [2]:
при выборе пункта AUTO_INCREMENT у вас появится окно, в нем просто нажмите [Вперёд]:
Сохраняем внесенные изменения, теперь таблица исправна. При необходимости, по аналогии с term_id, выполняем вышеописанные действия для других таблиц.
Благодарности
При написании статьи были использованы следующие источники:
- http://langui.net/2012/01/alter-table-auto_increment-resequencing-resulting-duplicate-entry-1-key-primary/
- http://got-quadrat.ru/blog/pochinka-klyuchej-u-tablits-wordpress-pri-kolliziyah/
A screw-up we now and again see in MySQL servers while reviving, “MYSQL Error 1062 Duplicate Entry for Key Primary”. Restoring or copying databases is: Error No: 1062 or Error Code: 1062 or ERROR 1062 (23000)
Around here at ARZHOST, couldn’t execute the Write rows event on the table my database name. table; Duplicate segment 174465 for key PRIMARY, Error code: 1062; regulator error HA_ERR_FOUND_DUPP_KEY; the events ace log MySQL-bin.000004, end_log_pos 60121977
What is MySQL Error No: 1062?
“MYSQL Error 1062 Duplicate Entry for Key Primary”, screw up 1062 is shown when MySQL notices a DUPLICATE of a segment. You are endeavoring to implant.
We’ve seen essentially 4 clarifications behind this error:
- The web application has a bug that adds fundamental key by gigantic options and drains quite far.
- MySQL bunch replication endeavors to re-install a field.
- An informational collection dump record contains duplicate lines because of a coding error.
- MySQL list table has duplicate segments.
In phenomenal cases, this mix-up is shown when the table ends up being excessively wonderful. “MYSQL Error 1062 Duplicate Entry for Key Primary” yet let’s not worry about that for the present.
Bit by bit directions to fix Error No 1062 when your web application is broken
Every database-driven application like WordPress, Drupal. Open Cart remembers one customer or helpful record from another using something many allude to as a fundamental field. This fundamental field should be recorded for each customer, post, etc
Web applications use a code like this to insert data:
Expansion INTO table ('id','field1','field2','field3') VALUES ('NULL','data1','data2','data3');
Where it is the exciting primary key, “MYSQL Error 1062 Duplicate Entry for Key Primary” and is set to auto-increment. (That is a number installed will reliably be more unmistakable than the beyond one to avoid duplicates).
This will work right if the value inserted is NULL and the informational index table is set to auto-increment. Some web applications, unfortunately, pass the value as
Characteristics ('','data1','data2','data3');
Where the essential field is barred. This will insert sporadic numbers into the fundamental field, rapidly growing the number to the best field limit (typically 2147483647 for numbers).
“MYSQL Error 1062 Duplicate Entry for Key Primary” All following requests will again effort to over-create the field with 2147483647, which MySQL unties as a Duplicate.
Web application error game plan
Exactly when we see a potential web application code error. The specialists at our Website Support Services make a fix to the application report that fixes the informational index question.
We have the non-sequential fundamental key table to be fixed. For that, we make another part (otherwise called field), set it as auto-expansion. A while later make it the fundamental key.
The code checks out along these lines:
- change table table1 drop fundamental key;
- change table table1 add field2 into the not invalid auto-increment fundamental key;
At the point when the fundamental key fields are stacked up with progressive characteristics, the name of the new field can be changed to the past one. So that all web application requests will proceed as in the past. These orders can get very amazing, amazingly fast. “MYSQL Error 1062 Duplicate Entry for Key Primary” if you don’t have the foggiest idea. How these commands work, it’s best to get ace assistance.
People Also Ask
Question # 1: What is meant by the duplicate entry for key primary?
Answer: When creating a primary key or unique constraint after loading the data, you can get a “Duplicate entry for key ‘PRIMARY’” error. If the data in the source database is valid and there are no duplicates you should check which collation is used in your MySQL database.
Question # 2: What is a duplicate entry?
Answer: Definition of duplicate (Entry 3 of 3) 1a: either of two things exactly alike and usually produced at the same time or by the same process. b: an additional copy of something (such as a book or stamp) already in a collection. 2: one that resembles or corresponds to another counterpart.
Question # 3: How do I fix a duplicate entry in MySQL?
Answer: Unique values are labeled with row number 1, while duplicates are 2, 3, and so on. Therefore, to remove duplicate rows. You need to delete everything except the ones marked with 1. This is done by running a DELETE query with the row_number as the filter.
Read More————
Question # 4: How do I ignore duplicate records in SQL?
Answer: To remove duplicates from a result set, you use the DISTINCT operator in the SELECT clause as follows: SELECT DISTINCT column1, column2, FROM table1; If you use one column after the DISTINCT operator. The database system uses that column to evaluate duplicates.
Question # 5: How do you prevent duplicates in SQL queries?
Answer: When the result set from a SELECT statement contains duplicate rows. You may want to remove them and keep every row data to be unique for a column or combination of columns. You can use the DISTINCT or DISTINCTROW identifier to eliminate duplicate records.
The best strategy to fix MySQL replication Error Code: 1062
As a result of variability’s in the organization or harmonizing MySQL is once in a known effort to create a section when it is free in the slave. Subsequently, when we see this slip-up in a slave, we effort both of the going with depending upon many elements, for instance, DB create traffic, period of the day, etc
- Remove the segment – This is the quicker and safer method of continuing if you understand that the line being formed is just about as old as of now present.
- Skirt the line – If you don’t know there be a data accident, “MYSQL Error 1062 Duplicate Entry for Key Primary”, you can have a go at keeping away from the line.
Bit by bit guidelines to delete the line
“MYSQL Error 1062 Duplicate Entry for Key Primary” First remove the line using the fundamental key.
- remove from table1 where field1 is key1;
Then, respite and start the slave:
stop slave;
start slave;
select sleep (5);
At whatever point it is done, “MYSQL Error 1062 Duplicate Entry for Key Primary” truly investigates the slave status to check whether replication is continuing.
show slave status;
On the off chance that everything is extraordinary, you’ll believe “MYSQL Error 1062 Duplicate Entry for Key Primary”, Seconds_Behind_Master to be a number. If not, your replication is broken and it ought to be fixed.
The best technique to keep away from the line
“MYSQL Error 1062 Duplicate Entry for Key Primary”, For this, you can set the Skip counter to 1.
Here’s how it could look like:
stop slave;
set overall SQL_SLAVE_SKIP_COUNTER = 1;
start slave;
select sleep (5);
Then, truly investigate the slave status to check whether replication is continuing.
show slave status;
Again, on the off chance that everything is incredible. You’ll believe “MYSQL Error 1062 Duplicate Entry for Key Primary”, Seconds_Behind_Master to be a number. If not, your replication is broken and it ought to be fixed.
Proceed cautiously
Ending and starting the slave can’t cause any issue except if you have an outstandingly clamoring database for any situation. The remove clarification, skipping, and returning to a wrecked replication requires ace data about MySQL affiliation and working
If you don’t have the foggiest idea of what these orders will mean for your database. “MYSQL Error 1062 Duplicate Entry for Key Primary” we approve your chat with a DB director.
The best strategy to fix MySQL restore errors
“MYSQL Error 1062 Duplicate Entry for Key Primary”, Restore error generally show up as:
Screw up 1062 (23000) at line XXXX: Duplicate segment XXXXXX for key X
While restoring informational index dumps, this error can happen given 2 reasons:
- The SQL dump record has duplicate areas.
- The record archive is duplicate lines.
To find what is turning out gravely. We look at the consistent lines and check whether they have something almost identical or different data. Expecting its comparable data, the issue could be a result of duplicate rundown lines. If it is different data, the SQL dump record ought to be fixed.
Guidelines to fix duplicate sections in database dumps
The current situation can happen when something like two tables is dumped into a singular report without checking for duplicates. To decide this, the single heading we’ve used is to make one more fundamental key field with auto-expansion. subsequently, change the requests to implant NULL value into it.
Then, continue with the landfill. At the point when the new fundamental field table is populated, “MYSQL Error 1062 Duplicate Entry for Key Primary”, the name of the field is changed to the old fundamental table name to save the old inquiries.
The change table request will look like this:
- adjust table table1 change portion ‘new primary’ ‘old primary’ varchar (255) not invalid;
If your record report is polluted
There’s no upfront method of fixing a documented record if there are duplicate areas in it.
You’ll need to delete the record archive and restore that report either from lines or from another server. Where your informational index dump is restored to another DB server. The means included are extremely minded confusing to run through here. “MYSQL Error 1062 Duplicate Entry for Key Primary” We recommend that you counsel a DB ace if you hypothesize the rundown record is damaged.
Conclusion
MySQL error no 1062 can happen in light of buggy web applications, damaged dump records, or replication issues. “MYSQL Error 1062 Duplicate Entry for Key Primary” Today at ARZHOST, we’ve seen the various habits by which the justification behind this error can be recognized. How it might be settled.
[Solved] How to solve MySQL error code: 1062 duplicate entry?
January 21, 2016 /
Error Message:
Error Code: 1062. Duplicate entry ‘%s’ for key %d
Example:
Error Code: 1062. Duplicate entry ‘1’ for key ‘PRIMARY’
Possible Reason:
Case 1: Duplicate value.
The data you are trying to insert is already present in the column primary key. The primary key column is unique and it will not accept the duplicate entry.
Case 2: Unique data field.
You are trying to add a column to an existing table which contains data and set it as unique.
Case 3: Data type –upper limit.
The auto_increment field reached its maximum range.
MySQL NUMERICAL DATA TYPE — STORAGE & RANGE |
Solution:
Case 1: Duplicate value.
Set the primary key column as AUTO_INCREMENT.
ALTER TABLE ‘table_name’ ADD ‘column_name’ INT NOT NULL AUTO_INCREMENT PRIMARY KEY;
Now, when you are trying to insert values, ignore the primary key column. Also you can insert NULL value to primary key column to generate sequence number. If no value specified MySQL will assign sequence number automatically.
Case 2: Unique data field.
Create the new column without the assigning it as unique field, then insert the data and now set it as unique field now. It will work now!!!
Case 3: Data type-upper limit.
When the data type reached its upper limit, for example, if you were assigned your primary key column as TINYINT, once the last record is with the id 127, when you insert a new record the id should be 128. But 128 is out of range for TINYINT so MySQL reduce it inside the valid range and tries to insert it with the id 127, therefore it produces the duplicate key error.
In order to solve this, you can alter the index field, setting it into signed / unsigned INT/ BIGINT depending on the requirement, so that the maximum range will increase. You can do that by using the following command:
ALTER TABLE ‘table_name’ MODIFY ‘column_name’ INT UNSIGNED NOT NULL AUTO_INCREMENT;
You can use the following function to retrieve the most recently automatically generated AUTO_INCREMENT value:
mysql> SELECT LAST_INSERT_ID();
Final workaround:
After applying all the above mentioned solutions and still if you are facing this error code: 1062 Duplicate entry error, you can try the following workaround.
Step 1: Backup database:
You can backup your database by using following command:
mysqldump database_name > database_name.sql
Step 2: Drop and recreate database:
Drop the database using the following command:
DROP DATABASE database_name;
Create the database using the following command:
CREATE DATABASE database_name;
Step 3: Import database:
You can import your database by using following command:
mysql database_name < database_name.sql;
After applying this workaround, the duplicate entry error will be solved. I hope this post will help you to understand and solve the MySQL Error code: 1062. Duplicate entry error. If you still facing this issue, you can contact me through the contact me page. I can help you to solve this issue.
На днях я переносил один из своих сайтов на новый хостинг и столкнулся с проблемой. Подробно о том, как перенести сайт на другой хостинг я расскажу в одной из следующих статей, а пока расскажу о самой проблеме и ее решении.
Файлы сайта я скопировал быстро, сделал экспорт базы данных со старого хостинга, но при попытке импортировать таблицы в базу на новом хостинге возникла ошибка в My SQL вот такого вида:
Ошибка
SQL-запрос:
— — Дамп данных таблицы `rich_blc_instances` — INSERT INTO `rich_blc_instances` (`instance_id`, `link_id`, `container_id`, `container_type`, `link_text`, `parser_type`, `container_field`, `link_context`, `raw_url`) VALUES (1, 1, 1, ‘blogroll’, ‘Документация’, ‘url_field’, ‘link_url’, », ‘http://codex.wordpress.org/Заглавная_страница’), (2, 2, 2, ‘blogroll’, ‘Блог WordPress’, ‘url_field’, ‘link_url’, », ‘http://wordpress.org/news/’), (3, 3, 3, ‘blogroll’, ‘Форумы поддержки’, ‘url_field’, ‘link_url’, », ‘http://ru.forums.wordpress.org/’), (4, 4, 4, ‘blogroll’, ‘Плагины’, ‘url_field’, ‘link_url’, », ‘http://wordpress.org/extend/plugins/’), (5, 5, 5, ‘blogroll’, ‘Темы’, ‘url_field’, ‘link_url’, », ‘http://wordpress.org/extend/themes/’), (6, 6, 6, ‘blogroll’, ‘Обратная связь’, ‘url_field’, ‘link_url’, », ‘http://ru.forums.wordpress.org/forum/20’), (7, 7, 7, ‘blogroll’, ‘Планета WordPr[…]
Ответ MySQL:
#1062 — Duplicate entry ‘1’ for key ‘PRIMARY’
Так как в базах данных я полный чайник, пришлось копаться в интернете в поисках решения. На форумах довольно много записей от людей с подобной проблемой, но нигде нет четкого ответа – сделай вот так и так.
В общих чертах я проблему понял, но вот как ее решить было неясно. На всех форумах, где встречалось описание подобной ошибки, люди писали, что она возникает при попытке добавить записи из одной базы данных в уже существующую другую.
Но я импортировал базу данных в пустые таблицы, более того, таблицы создавались в процессе импорта.
Решил проблему с ошибкой «#1062 — Duplicate entry ‘1’ for key ‘PRIMARY’» следующим образом:
Заменил в таблицах базы данных команду INSERT INTO на REPLACE INTO. В тексте ошибки, который я привел выше вы можете посмотреть в каком месте таблицы располагаются эти слова (выделил жирным).
По умолчанию, с помощью директивы insert база пыталась вставить значения в таблицу, но почему-то, находила дублированный key ‘PRIMARY’ и не могла вставить данные (как она их находила, я так и не разобрался). Директива replace заставила базу заменять данные при совпадении значений, не обращая внимания на прошлые записи.
Заменить эту директиву можно открыв сам файл базы данных с помощью текстового редактора – эта команда стоит перед блоком каждой таблицы. Открываете базу данных в текстовом редакторе, например, Akelpad и меняете все команды INSERT INTO на REPLACE INTO.
В моем же случае, получилось сделать проще – я по новой сделал экспорт таблицы на старом хостинге и в настройках экспорта установил этот самый REPLACE вместо INSERT.