Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error Duplicate entry '1-11' for key 'user_image' when creating new UNIQUE index

My table structure:

CREATE TABLE `userimageview` (
  `user_id` int(11) unsigned NOT NULL,
  `image_id` int(11) unsigned NOT NULL,
  `thumbnail_view` int(10) unsigned NOT NULL,
  `fullsize_view` int(10) unsigned NOT NULL,
  `point` int(10) unsigned NOT NULL,
  KEY `everything` (`user_id`,`image_id`,`thumbnail_view`,`fullsize_view`,`point`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

The index that I'm going to add:

ALTER TABLE `userimageview` ADD UNIQUE `user_image` (`user_id` , `image_id`)

Result:

#1062 - Duplicate entry '1-11' for key 'user_image' 

How should I add my UNIQUE index?

like image 882
Mohammad Naji Avatar asked Apr 24 '12 01:04

Mohammad Naji


People also ask

How do I fix error 1062 in MySQL?

1062 - Duplicate Entry To solve this, Set the primary key column as AUTO_INCREMENT . And when you are trying to insert a new row, ignore the primary key column or insert NULL value to primary key.

What is duplicate entry for key primary?

You cannot have duplicate values in a primary key field. A primary key can also consist of multiple fields so what fields are in your key? Don't know for sure, but could your database have formed a relationship between shares and id ?

What is unique index in MySQL?

Indexing is a process to find an unordered list into an ordered list that allows us to retrieve records faster. It creates an entry for each value that appears in the index columns. It helps in maximizing the query's efficiency while searching on tables in MySQL.


1 Answers

Your newly added UNIQUE constraint is failing because your table already contains duplicate rows that violate it. Locate the constraint violators with a query like the following. You won't be able to add the UNIQUE index as long as these rows are present.

SELECT
  user_id, 
  image_id, 
  COUNT(*) AS dupes
FROM userimageview
GROUP BY user_id, image_id
HAVING dupes > 1
ORDER BY dupes DESC
like image 195
Michael Berkowski Avatar answered Oct 14 '22 00:10

Michael Berkowski