MySQL Tutorial
In MySQL, a JOIN is used to combine rows from two or more tables based on a related column.
Joins are essential when working with relational databases, allowing you to retrieve data from multiple tables in a single query.
Let's look at a selection from the "Students" table:
student_id |
name |
gender |
city |
age |
score |
course_id |
|
phone_number |
---|---|---|---|---|---|---|---|---|
1 |
Alice |
Female |
Delhi |
20 |
85 |
101 |
NULL |
1234567890 |
2 |
Bob |
Male |
Mumbai |
22 |
75 |
NULL |
bob@email.com |
NULL |
3 |
Charlie |
Male |
Delhi |
21 |
95 |
102 |
NULL |
NULL |
4 |
David |
Male |
Bangalore |
23 |
65 |
101 |
david@email.com |
NULL |
5 |
Eve |
Female |
Mumbai |
20 |
80 |
103 |
NULL |
NULL |
6 |
Frank |
Male |
Delhi |
22 |
90 |
103 |
NULL |
NULL |
7 |
Alice |
Female |
Mumbai |
19 |
60 |
102 |
NULL |
NULL |
Then, look at a selection from the "Course" table:
course_id |
course_name |
---|---|
101 |
Math |
102 |
Science |
103 |
History |
Notice that the "course_id" column in the "Course" table refers to the "course_id" in the "Students" table. The relationship between the two tables above is the "course_id" column.
Then, we can create the following SQL statement (that contains an INNER JOIN
), that selects records that have matching values in both tables:
Try it yourself
and it will produce something like this:
name |
course_name |
---|---|
Alice |
Math |
Charlie |
Science |
David |
Math |
Eve |
History |
Frank |
History |
Alice |
Science |