问题
I recently ran into a quite puzzling situation. In a table which has a unique constraint set on 2 fields, there are many existing records that violate this constraint!
And the main question is: How could they have gotten there in the first place, with the unique constraint already in place?
Schema:
CREATE TABLE `rest_service_mediafile` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`video_id` int(11) NOT NULL,
`video_encoding_id` int(11) NOT NULL,
`external_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `rest_service_mediafile_video_id_4a2efdd4_uniq` (`video_id`,`video_encoding_id`),
KEY `rest_service_mediafile_5d9d774` (`video_id`),
KEY `rest_service_mediafile_62de6709` (`video_encoding_id`),
CONSTRAINT `video_encoding_id_refs_id_3122bd65` FOREIGN KEY (`video_encoding_id`) REFERENCES `rest_service_videoencoding` (`id`),
CONSTRAINT `video_id_refs_id_567c8704` FOREIGN KEY (`video_id`) REFERENCES `rest_service_video` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=93154 DEFAULT CHARSET=utf8
Sample query: (but this is not the only duplicate)
mysql> select id, video_id, video_encoding_id, external_id from rest_service_mediafile where video_id = 157165 and video_encoding_id=2;
+-------+----------+-------------------+-------------+
| id | video_id | video_encoding_id | external_id |
+-------+----------+-------------------+-------------+
| 82416 | 157165 | 2 | 0 |
| 82424 | 157165 | 2 | 0 |
+-------+----------+-------------------+-------------+
And if I try an alter table query on some field like:
ALTER TABLE rest_service_mediafile
MODIFY external_id
varchar(255) NULL;
I will get the constraint error: The error was: (1062, "Duplicate entry '157165-2' for key 'rest_service_mediafile_video_id_4a2efdd4_uniq'")
Also if I try to simply insert a duplicate value, it will fail correctly! Any of you encountered a scenario in which this is possible in MySQL?
回答1:
Was the constraint added post hoc?
Bug: ALTER IGNORE TABLE t ADD UNIQUE INDEX does not delete duplicate rows in MySQL 5.1 and 5.5.
This is noted in the InnoDB docs as a Limitation of Fast Index Creation.
来源:https://stackoverflow.com/questions/12099230/table-with-unique-constraint-has-duplicate-records-mysql-5-1-57