您的位置:首页 > 数据库 > MySQL

mysql InnoDB表插入操作报duplicate entry for primary 却查询不到重复的主键

2017-01-12 15:07 951 查看
在腾讯实习的为数不多的最后几天日子里,碰到了一个很奇怪的mysql插入失败,具体情形如下:

这是show create table schedule_detail_material;的结果



这是show create table schedule_detail_material_online;的结果



即一个是线上排期素材表,一个是排期素材表。我现在要做的插入操作是要把排期素材表中的一条数据插入线上排期素材表中。那排期素材表称为A,线上排期表素材表称为B,就是A的数据插入B。

然而我执行插入操作:



主键重复?我看了下这个表是3个字段的复合主键,然后只报素材id 7415重复,那我先搜搜A表需要插入B表的数据是什么吧:



也就一条数据啊。那B表中是不是已经有这样的主键了呢?





没有!那怎么会报主键重复的错误呢?

我网上搜了搜,初步判定是数据库表文件损坏了,需要drop table后重新create。因为同样的代码,在测试环境则运行良好,但是到了正式环境则会报这个错误。然而我并没有胆量自己去recreate线上表,所以把问题抛给了我导师,期待他更好的处理方法。

---------------------------------------------------------------更新---------------------------------------------------------------------

导师和leader昨晚一起看这个问题,导师估计这个表从创建开始被改来改去(比如可能之前是一个主键,现在变成3个联合主键,因为报重复主键错只报material_id,不报schedule_id-adslot_id-material_id),表结构出现了问题。所以创建了一个同样名字的新表,将数据导了进去,问题解决了。原来的表则命名为:schedule_detail_material_online_1,还保留在里面,日后看看这个表到底咋回事。



---------------------------------------------------------------结束---------------------------------------------------------------------

理由一:来自:http://www.rathishkumar.in/2016/01/how-to-solve-mysql-error-code-1062.html

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.
ALTERTABLE‘table_name’ADD ‘column_name’INT NOTNULL AUTO_INCREMENT PRIMARYKEY;

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 / unsignedINT/ BIGINT depending on the requirement, so that
the maximum range will increase. You can do that by using the following command:
ALTERTABLE‘table_name’MODIFY ‘column_name’INT UNSIGNED NOTNULL 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.


理由二:来自:http://www.xmsdn.net/mysql/duplicate-entry-for-key-1/

¤ mysql错误:duplicate entry ‘ ‘ for key 1   无法自动插入到数据库,提示自增主键重复.

    今天在执行一个操作时发现老是不成功,后打印出错误sql 语句,发现无法插入. 于是仔细的查看插入语句,一点问题都没有,mysql报错是:Duplicate entry ’495131′ for key 1    ,重复的入口’495131′ 主键 id  ,而数据库中并没有 ’495131′ 这个id键值.  当时就纳闷了,到底是怎么事?

    后怀疑是数据库出了问题,网上搜索了下,果然有很多朋友遇到同样的问题,数据库被损坏了,解决的方法就是修复该表.  (注意:修复前将数据库备份,因为无法保证修复后会丢失多少数据.)

具体方法: 

1.  简单修复:

进入mysql输入命令:       repair table  table_name ;        //table_name  换成要修复的表名 .

另修复命令:      #  mysqlcheck -A -o -r Database_NAME  - p 

2. 全部数据库修复:

命令  :  mysqlcheck  -A -o -r -uroot -ppasswd    (注意,将root用户名和passwd密码改为你的MySQL的密码)

3. Navicat mysql工具修复:

开启Navicat 右键单击表,选择–维护表-》修复表-》快速. 即可.

另:  还有一种无法自动插入数据的原因就是此时插入自增id超过了它的范围.
理由三:来自:http://stackoverflow.com/questions/13132535/mysql-duplicate-entry-error-even-though-there-is-no-duplicate-entry


MySQL
duplicate entry error even though there is no duplicate entry

up
vote6down
votefavorite
1

I am using MySQL 5.1.56, MyISAM. My table looks like this:
CREATE TABLE IF NOT EXISTS `my_table` (
`number` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`money` int(11) NOT NULL,
PRIMARY KEY (`number`,`name`)
) ENGINE=MyISAM;


It contains these two rows:
INSERT INTO `my_table` (`number`, `name`, `money`) VALUES
(1, 'S. Name', 150), (2, 'Another Name', 284);


Now I am trying to insert another row:
INSERT INTO `my_table` (`number`, `name`, `money`) VALUES
(2, 'S. Name', 240);


And MySQL just won't insert it while telling me this:
#1062 - Duplicate entry '2-S. Name' for key 'PRIMARY'


I really don't understand it. The primary key is on the first two columns (both of them), so the row I am trying to insert HAS a unique primary key, doesn't it?

I tried to repair the table, I tried to optimize the table, all to no avail. Also please note that I cannot change from MyISAM to InnoDB.

Am I missing something or is this a bug of MySQL or MyISAM? Thanks.

To summarize and point out where I think is the problem (even though there shouldn't be):Table has primary key on two columns. I am trying to insert a row with a new combination of values in these two
columns, but value in column one is already in some row and value in column two is already in another row. But they are not anywhere combined, so I believe this is supposed to work and I am very confused to see that it doesn't.

mysql primary-key mysql-error-1062 duplicates
shareimprove
this question
edited Oct
30 '12 at 4:32

asked Oct 30 '12 at 4:13





user1763581
1551314

 
 
Are those the exact schema and exact 
INSERTs
?
If not, we may be barking up the wrong trees! Please provide a reproducible test case. – Rick
James Oct
8 '16 at 5:24
add
a comment


10 Answers

activeoldestvotes

up vote10down
voteaccepted
Your code and schema are OK. You probably trying on previous version of table.

http://sqlfiddle.com/#!2/9dc64/1/0

Your table even has no UNIQUE, so that error is impossible on that table.

Backup data from that table, drop it and re-create.

Maybe you tried to run that 
CREATE
TABLE IF NOT EXIST
. It was not created, you have old version, but there was no error because of 
IF
NOT EXIST
.

You may run SQL like this to see current table structure:
DESCRIBE my_table;


Edit - added later:

Try to run this:
DROP TABLE `my_table`; --make backup - it deletes table

CREATE TABLE `my_table` (
`number` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`money` int(11) NOT NULL,
PRIMARY KEY (`number`,`name`),
UNIQUE (`number`, `name`) --added unique on 2 rows
) ENGINE=MyISAM;


shareimprove
this answer
edited Oct
30 '12 at 4:45

answered Oct 30 '12 at 4:30





Kamil
5,8391338100

 
 
Well thanks, I see that it works there but I just can't get it to work in my database :( – user1763581 Oct
30 '12 at 4:34
 
Read my answer again, i added some info. – Kamil Oct
30 '12 at 4:36
 
Thanks, I re-created the table, inserted data from the old table and tried again. There was no change in anything, but
after I ran the insert query on the new table, it worked. So the old table was probably somehow corrupted, even though I have no idea how. – user1763581 Oct
30 '12 at 4:46
 
It was probably old version of table. Your script that was supposed to update schema did nothing, because there was
"IF (table) NOT EXIST". – Kamil Oct
30 '12 at 4:49
1 
I didn't try the thing with adding UNIQUE, it worked with just re-creating and re-filling the table. – user1763581 Oct
30 '12 at 4:50 
 
UNIQUE is optional - if you want to keep unique value combination in these fields. Now - without UNIQUE - you should
be able to insert duplicate values for that key. – Kamil Oct
30 '12 at 4:51 
 
PRIMARY
KEY
 (in MySQL) is 
UNIQUE
.
So adding the 
UNIQUE
 key
is totally redundant (and wasteful). This applies to any Engine, not must MyISAM. – Rick
James Oct
8 '16 at 5:16
add
a comment



Did you find this question interesting? Try our newsletter

Sign up for our newsletter and get our top new questions delivered to your inbox (see
an example).

 

up vote3down
vote
I know this wasn't the problem in this case, but I had a similar issue of "Duplicate Entry" when creating a composite primary key:
ALTER TABLE table ADD PRIMARY KEY(fieldA,fieldB);


The error was something like:
#1062 Duplicate entry 'valueA-valueB' for key 'PRIMARY'


So I searched:
select * from table where fieldA='valueA' and fieldB='valueB'


And the output showed just 1 row, no duplicate!

After some time I found out that if you have NULL values in these field you receive these errors. In the end the error message was kind of misleading me.

shareimprove
this answer
answered Sep 3 '15 at 20:32





carla
492519

 add
a comment
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: