我有以下两个表:
StudentCourse
- Id,
- StudentId,
- CourseId
StudentId
和 CourseId
的唯一索引
StudentCourseCount
- Id,
- Student1Id,
- Student2Id,
- CourseCount
Student1Id
和 CourseCount
上的索引
Student2Id
和 CourseCount
上的索引
当我有一个 CourseId
时,我会列出参加该类(class)的学生。我想要完成的关键是在一个学生下面,我想列出他们以前一起上过课的其他学生。
我正在尝试以下查询:
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 多行)上 super 慢。
当我解释查询时,StudentCourseCount
不使用索引。它正确地识别出 Student1Id
和 Student2Id
可能存在索引,但两者都不使用。
Execution plan: Table: sc Possible keys: Student1Id, Student2Id Key: null Rows: 28648392
Table: c2 Key: student_id Rows: 1
Table: c1 Key: student_id Rows: 1
第一个表明显是扫描,没有使用key快速过滤
最佳答案
似乎您也应该将 course_id 过滤器放在外部选择中。 StudentCourseCount sc 上唯一的过滤器是 course_count。假设您只搜索 1 个 course_id,您应该有 sc.course_count>1 AND sc.course_id = id。否则,是您的联接试图将过滤器应用于 sc.course_count>1 个结果集。
假设值均匀分布,这个查询(或变体)应该是高性能的。 1000 万行并不是很大,它足够大,需要优化查询。
关于mysql - 未使用数据库索引导致查询缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24059835/