MySQL 共有三个表:
要连接所有三个表,我们只需要 PK 以及 courseid 的索引:
alter table enrollment add index (courseid);
查询:
select s.name, c.name, e.semesterid
from student s
join enrollment e on s.id=e.studentid
join course c on c.id=e.courseid;
解释计划:
+----+-------------+-------+--------+------------------+----------+---------+------------------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+------------------+----------+---------+------------------+------+-------------+
| 1 | SIMPLE | e | index | PRIMARY,courseid | courseid | 4 | NULL | 10 | Using index |
| 1 | SIMPLE | s | eq_ref | PRIMARY | PRIMARY | 4 | test.e.studentid | 1 | |
| 1 | SIMPLE | c | eq_ref | PRIMARY | PRIMARY | 4 | test.e.courseid | 1 | |
+----+-------------+-------+--------+------------------+----------+---------+------------------+------+-------------+
解释计划看起来很好,将使用索引,没有全表扫描。但问题来了,为什么计划只有三行?我希望有四排。我希望:
- 表学生 - 主键
- Table Enrollment - Primary Key <-- 我在计划中没有看到这个,为什么?
- 表格注册 - 索引 courseid
- 表类(class) - 主键
查询连接三个表,即两次连接两个表。这意味着我希望使用四个索引。
最佳答案
它最终会有一个表扫描(你没有where子句)
它将三个表链接在一起。两个债券。向下扫描一个并使用索引链接到另外两个。
计划中的三行
顺便说一句 - CourseID 其中两个的 PK 有帮助
编辑
为您更新。
没有 where 子句 - 所以需要一切 也没有排序
进入登记表格。使用 CourseID,因为它是主键。在另一个表中也得到了 courseid (Course)。
所以加入了。现在需要找到学生位。查看特定的注册所以得到学生 ID 所以使用学生中的 PK 来查找学生的详细信息。
入学不需要PK就可以入学
关于mysql - 为什么这个 MySQL 查询解释计划只有三行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20673297/