有三个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 | |
+----+-------------+-------+--------+------------------+----------+---------+------------------+------+-------------+
解释计划看起来很好,将使用索引,没有全表扫描。但问题是,为什么计划只有三行?我希望有四排。我希望:
查询连接三个表,这意味着连接两个表两次。这意味着我希望使用四个索引。
答案 0 :(得分:0)
它最终会有一个表扫描(你没有where子句)
它将三个表连接在一起。两个债券。向下扫描并使用索引链接到另外两个。
计划中的三行
BTW - 其中两个PK中的课程ID有助于
修改强>
供您更新。
没有where子句 - 所以需要一切 没有排序
按下注册表。使用CourseID,因为它是主键。在其他表格中也有课程(课程)。
所以加入了联盟。现在需要找到学生位。查看特定的注册表,以便获得学生证,所以请在学生中使用PK查找学生的详细信息。
入学时无需注册PK