← Back to Chapters

MySQL JOIN Multiple Tables

? MySQL JOIN Multiple Tables

? Quick Overview

MySQL allows joining multiple tables using the JOIN keyword. This enables combining related data from several tables into a single result set using common columns.

? Key Concepts

  • INNER JOIN – Matches records in both tables
  • LEFT JOIN – All rows from left table + matching right rows
  • RIGHT JOIN – All rows from right table + matching left rows
  • CROSS JOIN – Cartesian product of tables

? Syntax / Theory

? View Code Example
// Syntax for joining multiple tables
SELECT column1, column2
FROM table1
JOIN table2 ON table1.column = table2.column
JOIN table3 ON table2.column = table3.column;

? Code Examples

? students Table

? View Code Example
// Sample data from students table
id | name
---------
1  | Alice
2  | Bob

? courses Table

? View Code Example
// Sample data from courses table
id | course
-----------
1  | Math
2  | Science

? enrollments Table

? View Code Example
// Mapping students to courses
student_id | course_id
----------------------
1          | 1
2          | 2

⚙️ Joining the Tables

? View Code Example
// Joining three tables using INNER JOIN
SELECT students.name, courses.course
FROM students
JOIN enrollments ON students.id = enrollments.student_id
JOIN courses ON enrollments.course_id = courses.id;

? Live Output / Explanation

? View Output
// Result after joining all tables
name  | course
--------------
Alice | Math
Bob   | Science

? Interactive Explanation

This query starts from students, matches records in enrollments, and finally links to courses, ensuring data consistency across all tables.

? Use Cases

  • Student-course management systems
  • Employee-department-project mapping
  • E-commerce orders with customers and products

? Tips & Best Practices

  • Always define accurate ON conditions
  • Prefer INNER JOIN for strict matching
  • Use LEFT JOIN when optional data is needed

? Try It Yourself

  • Practice combining INNER and LEFT JOINs
  • Create additional tables like teachers and departments
  • Experiment with multi-level JOIN conditions