In MySQL, an inner join is used to combine rows from two or more tables based on a related column between them. An inner join returns only the rows where there is a match in both tables based on the specified join condition. The basic syntax for an inner join in MySQL is:
SELECT columns FROM table1 INNER JOIN table2 ON table1.column = table2.column;
In this syntax, columns
are the columns you want to select from the combined tables, table1
is the first table, table2
is the second table you want to join, and column
is the related column between the two tables.
Here’s an example of an inner join between two tables:
SELECT orders.order_id, customers.customer_name FROM orders INNER JOIN customers ON orders.customer_id = customers.customer_id;
In this example, the orders
table and the customers
table are joined using the customer_id
column, and only the records with matching customer IDs in both tables will be returned.
For example, consider two tables, employees
and departments
, where the departments
table has a column dept_id
that relates to the employees
table’s column dept_id
. We can use an inner join to get all the employees and their corresponding department names.
SELECT employees.employee_name, departments.department_name FROM employees INNER JOIN departments ON employees.dept_id = departments.dept_id;
In this example, the employees
table and the departments
table are joined using the dept_id
column, and only the records with matching department IDs in both tables will be returned, along with their corresponding employee and department names.