MySQL : INNER JOIN Keyword

In MySQL, the INNER JOIN keyword is used to combine rows from two or more tables based on a related column between them. It returns only the rows where there is a match between the columns in both tables.

Here's the basic syntax of the INNER JOIN:


SELECT columns
FROM table1
INNER JOIN table2 ON table1.column_name = table2.column_name;

 

  • columns: The columns you want to retrieve from the tables.
  • table1, table2: The names of the tables you want to join.
  • column_name: The column(s) that exist in both tables and are used to join them.

Example:

Let's say we have two tables: `employees` and `departments`. The `employees` table contains information about employees, including their department ID, and the `departments` table contains department names and their corresponding department IDs.

We want to retrieve the names of employees along with the names of their departments.


SELECT employees.first_name, employees.last_name, departments.department_name
FROM employees
INNER JOIN departments ON employees.department_id = departments.department_id;

 

In this query:

  • employees is the first table.
  • departments is the second table.
  • We specify the join condition using the ON keyword, which matches the department_id column from the employees table with the department_id column from the departments table.
  • The result will contain rows where there is a match between the department_id values in both tables.

The INNER JOIN returns only the rows where there is a match in both tables. If there is no match for a row in one table, that row will not be included in the result set.

INNER JOIN is the most commonly used type of join, and it's useful for retrieving related data from multiple tables based on a common key.