MySQL INNER JOIN
The INNER JOIN clause in MySQL 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 in both tables.
Syntax
ON
specifies the condition for joining the tables.- If no matching rows exist, those rows are excluded from the result.
Example Tables
Table: employees
Table: departments
1. Basic INNER JOIN
Retrieve a list of employees along with their department names:
Result
- Explanation: Only rows with matching
department_id
inemployees
andid
indepartments
are included.
2. INNER JOIN with Additional Conditions
Get employees from the "IT" department:
Result
3. INNER JOIN Across Multiple Tables
Consider another table, projects
:
Table: projects
Retrieve employees, their department names, and the projects they are working on:
Result
4. INNER JOIN with Aggregate Functions
Count the number of employees in each department:
Result
5. INNER JOIN with Aliases
For better readability, table aliases are often used.
Example
This produces the same result as the basic example but improves query clarity.
6. Combining INNER JOIN with ON
and USING
Using ON
Using USING
If the columns have the same name, you can use USING
:
7. INNER JOIN vs. Other Joins
- INNER JOIN: Returns rows with matching data in both tables.
- LEFT JOIN: Includes all rows from the left table, even if there's no match in the right table.
- RIGHT JOIN: Includes all rows from the right table, even if there's no match in the left table.
Best Practices for INNER JOIN
Use Indexing:
- Index the columns used in the
ON
condition for faster query performance.
- Index the columns used in the
Use Aliases:
- Use shorter aliases (e.g.,
e
,d
) for tables in complex queries.
- Use shorter aliases (e.g.,
Avoid Unnecessary Columns:
- Select only the columns you need to improve performance.
Let me know if you'd like further assistance or additional examples!