错误在创建新的UNIQUE索引时,为“user_image”键复制条目“1-11”

时间:2012-04-24 01:19:30

标签: mysql indexing unique mysql-error-1062

我的表结构:

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;

我要添加的索引:

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

结果:

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

我应该如何添加UNIQUE索引?

1 个答案:

答案 0 :(得分:11)

您新添加的UNIQUE约束失败,因为您的表已经包含违反它的重复行。使用如下查询找到约束违反者。只要这些行存在,您将无法添加UNIQUE索引。

SELECT
  user_id, 
  image_id, 
  COUNT(*) AS dupes
FROM userimageview
GROUP BY user_id, image_id
HAVING dupes > 1
ORDER BY dupes DESC