Joins and Relationships in MySQL
💻 MySQLQuery related tables and keep relationships consistent with foreign keys.
MySQL does not store relationships inside a row. It stores ids and connects tables at query time with joins.
- Write INNER and LEFT joins.
- Use foreign keys correctly.
- Avoid duplicate rows in multi-table queries.
A Simple Join
Join on the matching id columns and select only the columns you need.
SELECT s.name, c.title
FROM students s
INNER JOIN enrolments e ON e.student_id = s.id
INNER JOIN courses c ON c.id = e.course_id
WHERE s.level = 'SS2';LEFT JOIN
Use LEFT JOIN when the related row is optional. This report includes students with no enrolments.
SELECT s.name, COUNT(e.id) AS courses
FROM students s
LEFT JOIN enrolments e ON e.student_id = s.id
GROUP BY s.id, s.name
ORDER BY courses DESC;Referential Integrity
A foreign key guarantees that an enrolment cannot reference a student that does not exist. Add indexes on foreign key columns for fast joins.
Practice
- List courses with the number of enrolled students.
- Find students with no enrolments.
- Explain what happens when you delete a parent row with ON DELETE CASCADE.
Hands-on exercise
Write a query that returns each course title and the names of enrolled students, including courses with no students. Order by course title, then student name.
Recap
Joins combine tables on matching keys. LEFT JOIN keeps unmatched parents, and foreign keys keep references valid.
Example
SELECT s.name, c.title
FROM students s
INNER JOIN enrolments e ON e.student_id = s.id
INNER JOIN courses c ON c.id = e.course_id
WHERE s.level = 'SS2';
Exercises
Expected Output
Every course appears at least once, with NULL student when empty.
Lesson Nav
MySQL Course
0/9 lessons completed
- 1 Connecting to MySQL Tutorial
- 2 Creating Databases and Tables Tutorial
- 3 Data Types and Constraints Tutorial
- 4 Reading and Writing Data Tutorial
- 5 Joins and Relationships in MySQL Tutorial
- 6 Functions, Dates and Text Tutorial
- 7 Views and Stored Procedures Tutorial
- 8 Users, Permissions and Backups Tutorial
- 9 Project: A Small School Database Project