There are three MySQL tables:
To join all three tables, all we need are the PKs, plus an index for courseid:
alter table enrollment add index (courseid);
The query:
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;
The explain plan:
+----+-------------+-------+--------+------------------+----------+---------+------------------+------+-------------+
| 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 | |
+----+-------------+-------+--------+------------------+----------+---------+------------------+------+-------------+
Explain plan looks fine, indexes will be used, with no full table scans. But here is the question, why does the plan have only three rows? I would expect four rows. I would expect:
- Table Student - Primary Key
- Table Enrollment - Primary Key <-- this one I dont see in the plan, why?
- Table Enrollment - index courseid
- Table Course - Primary Key
The query joins three tables, that means two times joining two tables. That means I expect four indexes to be utilized.
It will eventually have a table scan (you have no where clause)
It is linking three tables together. Two bonds. Scan down one and use the indexes to link to the other two.
Three rows in the plan
BTW - CourseID a PK in two of them helps
EDIT
For your update.
No where clause - So need everything No sorting either
Go down the Enrolment table. Use the CourseID as it is the primary key. Got the courseid in the other table as well (Course).
So got a join down. Now need to find the student bit. looking at a particular enrolment so got the student ID so use the PK in the student to find the details of the student.
No need for the PK in enrolment for enrolment