mysql - 未使用数据库索引导致查询缓慢

标签 mysql sql database-indexes

我有以下两个表:

StudentCourse
- Id, 
- StudentId, 
- CourseId  

StudentIdCourseId 的唯一索引

StudentCourseCount
- Id, 
- Student1Id, 
- Student2Id, 
- CourseCount  

Student1IdCourseCount 上的索引

Student2IdCourseCount 上的索引

当我有一个 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 不使用索引。它正确地识别出 Student1IdStudent2Id 可能存在索引,但两者都不使用。

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/

相关文章:

java - Vaadin MySQL 获取

mysql - 在 Mysql 中更新表的属性时触发

php - mySQL 语句的第一个词不能是 DELETE 或 UPDATE

sql - 要列出的缓存 SQL 列

sql-server-2008 - SQL Server 2008 : How to count all indexes on all tables in Database?

MySQL insert, update-heavy, 按索引排序

php - php表格中的复选框

php - 嵌套集模型 : Query node childs only 1 level below AND all parents above

sql - vb6 ADODB 连接字符串到 sql server 2008

postgresql - Postgres 对一个非常简单的 SELECT x ... ORDER BY x 进行 Seq Scan 而不是 Index Only Scan