INNER JOIN is a type of join in MySQL that returns only the rows that have matching values in both tables.
Example:
You have two tables: students and courses.
The students table contains information about students, and the courses table contains information about courses.
Each student can enroll in multiple courses, so there's a relationship between the two tables.
Tables:
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(100),
age INT
);
CREATE TABLE courses (
id INT PRIMARY KEY,
name VARCHAR(100),
student_id INT,
FOREIGN KEY (student_id) REFERENCES students(id)
);
And let's say you have some sample data in these tables:
Table1 - students :
id | name | age |
1 | Mahendra | 10 |
2 | Lokendra | 20 |
3 | Shivam | 30 |
Table2 - courses :
id | name | student_id |
1 | Math | 1 |
2 | Physics | 2 |
3 | Chemistry | 1 |
4 | Biology | 3 |
5 | History | 2 |
Now, if you want to retrieve a list of courses along with the names of the students who are enrolled in those courses, you can use an INNER JOIN:
Mysql Query:
SELECT courses.name AS course_name, students.name AS student_name FROM courses INNER JOIN students ON courses.student_id = students.id;
This query will join the courses table with the students table using the student_id column in the courses table and the id column in the students table. It will then select the course name from the courses table and the student name from the students table.
Output:
course_name | student_name |
Math | Mahendra |
Physics | Lokendra |
Chemistry | Mahendra |
Biology | Shivam |
History | Lokendra |