Ошибка 1062 mysql как исправить

Это статья является логическим продолжением моего поста Ошибки 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 должна выглядеть так:
error-1062_0

У меня в неисправной таблице wp_term отсутствовало значение auto_increment для term_id, что приводило к некорректной работе WordPress. В частности было невозможности создать новую Рубрику для записей.
error-1062_1

Если при использовании SQL запроса

ALTER TABLE wp_term CHANGE term_id `term_id` bigint(20) unsigned NOT  AUTO_INCREMENT;

или редактирования в phpmyadmin
error-1062_2

вы получили сообщение об ошибке «ERROR 1062: ALTER TABLE causes auto_increment resequencing..», то удалите это поле (строку) [1]…
error-1062_3

… а затем создайте заново [2]:
error-1062_4

при выборе пункта AUTO_INCREMENT у вас появится окно, в нем просто нажмите [Вперёд]:
error-1062_5

Сохраняем внесенные изменения, теперь таблица исправна. При необходимости, по аналогии с term_id, выполняем вышеописанные действия для других таблиц.

Благодарности

При написании статьи были использованы следующие источники:

  1. http://langui.net/2012/01/alter-table-auto_increment-resequencing-resulting-duplicate-entry-1-key-primary/
  2. http://got-quadrat.ru/blog/pochinka-klyuchej-u-tablits-wordpress-pri-kolliziyah/

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!

I’m trying to insert a huge list of users to a MySQL database but everytime I try I get the error:

#1062 - Duplicate entry '' for key 2

It gives me this because the 2nd column is blank on quite a lot of the entries, so after it’s inserted one blank entry in column 2, it won’t let me add another. However, when I added most of the list yesterday I didn’t get this error once even though a lot of the entries I added yesterday have a blank cell in column 2 as well. Whats going on?

This is the sql code to insert 1 entry. The rest follow the same format:

INSERT INTO users
  (`id`,`title`,`firstname`,`lastname`,`company`,`address`,`city`,`county`
   ,`postcode`,`phone`,`mobile`,`category`,`email`,`password`,`userlevel`) 
VALUES     
  ('','','John','Doe','company','Streeet','city','county'
  ,'postcode','phone','','category','emial@email.co.uk','','');

На днях я переносил один из своих сайтов на новый хостинг и столкнулся с проблемой. Подробно о том, как перенести сайт на другой хостинг я расскажу в одной из следующих статей, а пока расскажу о самой проблеме и ее решении.

Файлы сайта я скопировал быстро, сделал экспорт базы данных со старого хостинга, но при попытке импортировать таблицы в базу на новом хостинге возникла ошибка в 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.

Карта Tinkoff Black

[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.

Понравилась статья? Поделить с друзьями:
  • Ошибка 1088 камаз 5490
  • Ошибка 1062 bmw
  • Ошибка 1087 камаз 5490
  • Ошибка 1085 мерседес
  • Ошибка 10617 ауди а6 с7