X
MySQL JOIN - Combining Data from Multiple Tables
JOIN is an SQL command that allows combining data from two or more tables into one
result. MySQL supports different types of JOIN commands:
-
INNER JOIN: Returns only records that match in both tables
- Returns only rows where values match in both tables
- Most commonly used type of JOIN
- Example: List of employees with their departments
-
LEFT JOIN (or LEFT OUTER JOIN): Returns all records from the left table and matching
records from the right
- Returns all records from the left table and matching records from the right
- If no match, values from the right are NULL
- Useful for displaying all records from the main table
-
RIGHT JOIN (or RIGHT OUTER JOIN): Returns all records from the right table and matching
records from the left
- Returns all records from the right table and matching records from the left
- Works similar to LEFT JOIN, but keeps all records from the right table
- Less commonly used, usually LEFT JOIN can be used instead
- FULL JOIN: Returns all records from both tables (simulated with UNION in MySQL)
JOIN commands are used with ON or USING clause to specify join conditions.
-
Using JOIN commands:
- Identify tables you want to join
- Choose appropriate JOIN type based on needs
- Define join condition with ON or USING
-
Best practices
- Always use table aliases
- Clearly define join conditions
- Be careful with NULL values in outer joins
-
In this example, we have two tables:
- departments: contains data about departments (dept_id, dept_name)
- employees: contains data about employees (emp_id, name, dept_id, manager_id)
The tables are linked via the dept_id field. Below is an example of an INNER JOIN:
SELECT e.name, d.dept_name FROM employees e INNER JOIN departments d ON e.dept_id = d.dept_id;
-
INNER JOIN displays only those employees and departments where a match exists:
SELECT e.name, d.dept_name FROM employees e INNER JOIN departments d ON e.dept_id = d.dept_id;
-
LEFT JOIN displays all employees, even if they do not have a department assigned:
SELECT e.name, d.dept_name FROM employees e LEFT JOIN departments d ON e.dept_id = d.dept_id;
-
RIGHT JOIN displays all departments, even those without any employees:
SELECT e.name, d.dept_name FROM employees e RIGHT JOIN departments d ON e.dept_id = d.dept_id;
-
CROSS JOIN displays all possible combinations of employees and departments:
SELECT e.name AS employee, d.dept_name FROM employees e CROSS JOIN departments d;
-
Self JOIN on the employees table allows us to display managers:
SELECT e1.name AS employee, e2.name AS manager FROM employees e1 LEFT JOIN employees e2 ON e1.manager_id = e2.emp_id ORDER BY e1.name;
We use cookies for a better user experience and website functionality.
Read more!
Thank you for visiting! Adding privacy policy.
© 2024 All rights reserved.
Vam je koda pomagala? Če želite podpreti moj trud pri pripravi vodičev in vzdrževanju strani, mi lahko
namenite donacijo za kavo.