【发布时间】:2014-06-05 12:08:11
【问题描述】:
我有以下两张表:
StudentCourse
- Id,
- StudentId,
- CourseId
StudentId 和 CourseId 上的唯一索引
StudentCourseCount
- Id,
- Student1Id,
- Student2Id,
- CourseCount
Student1Id 和 CourseCount 的索引
Student2Id 和 CourseCount 上的索引
当我有CourseId 时,我会列出参加该课程的学生。我想要完成的关键是在一个学生下,我想列出他们以前一起学习过的其他学生。
我正在尝试以下查询:
SELECT * FROM StudentCourseCount sc
INNER JOIN StudentCourse s1 ON s1.course_id = <id> AND sc.student1_id = s1.student_id
INNER JOIN StudentCourse s2 ON s2.course_id = <id> AND sc.student2_id = s2.student_id
WHERE sc.course_count > 1
查询按预期工作;但是,在我的超大表(超过 10,000,000 行)上它非常慢。
当我解释查询时,StudentCourseCount 不使用索引。它正确识别出Student1Id 和Student2Id 可能存在索引,但两者都不使用。
执行计划:表:sc 可能的键:Student1Id,Student2Id 键: 空行:28648392
表:c2 键:student_id 行:1
表:c1 键:student_id 行:1
第一个表明显是在扫描,没有用key快速过滤。
【问题讨论】:
-
你能复制一下你的表的执行计划和索引定义吗?
-
我只是好奇。 . .哪个应用程序在
StudentCourse表中有 10,000,000 行? -
我已经添加了索引并描述了查询执行计划(它没有很好地复制/粘贴,所以我重新编写了重要的部分)。
-
专业提示:避免在软件中使用
SELECT *,尤其是在访问大型表的查询中。返回所有列的需要会使优化器难以巧妙地满足您的查询。如果您重写查询以枚举所需的列,您将帮助我们推荐有用的索引策略。 -
如果它在 StudentCourseCount 上进行表扫描,我猜
WHERE sc.course_count > 1的选择性不够
标签: mysql sql database-indexes