Joining Tables
In MySQL, JOIN
operations are used to combine rows from two or more tables based on a related column between them. Here's an explanation of the different types of joins:
The INNER JOIN keyword selects records that have matching values in both tables.
SELECT columns
FROM table1
INNER JOIN table2
ON table1.common_column = table2.common_column;
Example
Assume we have two tables, students and enrollments.
SELECT students.id, students.first_name, students.last_name, enrollments.course_id
FROM students
INNER JOIN enrollments ON students.id = enrollments.student_id;
2. LEFT JOIN (or LEFT OUTER JOIN)
The LEFT JOIN keyword returns all records from the left table (table1), and the matched records from the right table (table2). The result is NULL from the right side if there is no match.
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.common_column = table2.common_column;
Example
SELECT students.id, students.first_name, students.last_name, enrollments.course_id
FROM students
LEFT JOIN enrollments ON students.id = enrollments.student_id;
This query returns all students, including those who are not enrolled in any courses. For students not enrolled,
course_id
will be NULL.3. RIGHT JOIN (or RIGHT OUTER JOIN)
The RIGHT JOIN keyword returns all records from the right table (table2), and the matched records from the left table (table1). The result is NULL from the left side if there is no match
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.common_column = table2.common_column;
4. FULL JOIN (or FULL OUTER JOIN)
The FULL JOIN keyword returns all records when there is a match in either left (table1) or right (table2) table records. Note that MySQL does not support FULL OUTER JOIN directly, but it can be simulated using a combination of LEFT JOIN and RIGHT JOIN with UNION.
SELECT columns
FROM table1
LEFT JOIN table2 ON table1.common_column = table2.common_column
UNION
SELECT columns
FROM table1
RIGHT JOIN table2 ON table1.common_column = table2.common_column;
Comments
Post a Comment