An INNER JOIN in SQL combines rows from two tables based on a specified condition. It returns only the rows where there is a match in both tables. Non-matching rows from either table are excluded from the results.
Syntax
The basic syntax for the INNER JOIN clause in MySQL is:
SELECT table1.column1, table2.column2,...
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;
In this syntax:
table1 and table2: These are the names of the tables you want to join.
table1.column1, table2.column2, ...: These are the names of the columns you want to select.
matching_column: This is the column that the two tables have in common, which is used to match rows between the two tables.
Demo Database
For the demonstration, we'll use our SchoolDB database. Our focus will be on the Students table and the Courses table.
The Students table includes student_id, first_name, last_name, grade_level columns:
The Courses table includes course_id, course_name, and student_id columns:
Examples
Let's take a look at the INNER JOIN clause in action.
Basic INNER JOIN
To get a list of students (first_name, last_name) and the courses (course_name) they are enrolled in, use:
SELECT Students.first_name, Students.last_name, Courses.course_name
FROM Students
INNER JOIN Courses
ON Students.student_id = Courses.student_id;
This statement returns a list of students and the respective courses they're enrolled in.
INNER JOIN with Additional Conditions
You can add a WHERE clause to the INNER JOIN statement to filter results. For instance, to find all courses taken by students in the 12th grade, use:
SELECT Students.first_name, Students.last_name, Courses.course_name
FROM Students
INNER JOIN Courses
ON Students.student_id = Courses.student_id
WHERE Students.grade_level = 12;
This statement fetches all courses taken by students in the 12th grade.
When to Use INNER JOIN
Scenario: Suppose you have two tables, Customers and Orders. If you wish to list all customers who have made at least one order, you'd use an INNER JOIN on the customer ID in both tables.
Summary
The INNER JOIN clause in MySQL is a powerful tool for combining data from two or more tables. By mastering the INNER JOIN clause, you're able to handle complex data structures and relationships, increasing your proficiency in database management. It's an essential skill in your SQL toolkit, allowing you to unlock the full potential of relational databases.
Comments
Post a Comment