msql索引

Posted 文静~

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了msql索引相关的知识,希望对你有一定的参考价值。

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

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

解决方案一: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索引的主要内容,如果未能解决你的问题,请参考以下文章

msql索引

Msql入门实战之下

Msql入门实战之下

msql_createdb: 建立一个新的 mSQL 数据库。

Msql浅析-基础命令

dokcerfile 制作Msql镜像