码迷,mamicode.com
首页 > 数据库 > 详细

msql索引

时间:2018-02-09 15:01:34      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:sql   desc   let   col   而且   alter   str   using   lte   

从网上找了两种解决方案:

最近要给一个表加一个联合唯一索引,但是表中的两个联合健有重复值,导致无法创建;

解决方案一: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);

msql索引

标签:sql   desc   let   col   而且   alter   str   using   lte   

原文地址:https://www.cnblogs.com/tong2018/p/8427409.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!