从网上找了两种解决方案:
最近要给一个表加一个联合唯一索引,但是表中的两个联合健有重复值,导致无法创建;
解决方案一:ignore(会删除重复的记录(重复记录只保留一条,其他的删除),然后建立唯一索引,高效而且人性化)
ALTER ignore TABLE `pr_tch_stu_elective`
ADD UNIQUE INDEX `Unique_ele` (`FK_STU_ID`, `FK_COURSE_ID`) USING BTREE ;
解决方案二:删除重复数据(未测试)
1.查询重复数据(2选1)
1)SELECT a.* FROM `pr_tch_stu_elective` a
INNER JOIN (SELECT * FROM `pr_tch_stu_elective` GROUP BY `FK_COURSE_ID`, `FK_STU_ID` HAVING COUNT(id) > 1) b ON a.`FK_COURSE_ID` = b.`FK_COURSE_ID` AND a.`FK_STU_ID` = b.`FK_STU_ID`
ORDER BY a.`FK_STU_ID` ASC, a.`FK_COURSE_ID` ASC, a.`id` DESC ;
2)SELECT * FROM `pr_tch_stu_elective`
WHERE (`FK_STU_ID`, `FK_COURSE_ID`) IN (SELECT `FK_STU_ID`, `FK_COURSE_ID` FROM `pr_tch_stu_elective` GROUP BY `FK_STU_ID`, `FK_COURSE_ID` HAVING COUNT(1) > 1);
2.删除重复数据
DELETE FROM `pr_tch_stu_elective`
WHERE (`FK_STU_ID`, `FK_COURSE_ID`) IN (SELECT `FK_STU_ID`, `FK_COURSE_ID` FROM (SELECT * FROM `pr_tch_stu_elective`) a GROUP BY `FK_STU_ID`, `FK_COURSE_ID` HAVING COUNT(1) > 1)
AND `id` NOT IN (SELECT MIN(`id`) FROM (SELECT * FROM `pr_tch_stu_elective`) b GROUP BY `FK_STU_ID`, `FK_COURSE_ID` HAVING COUNT(1) > 1);