In MySQL, joins are used to combine rows from two or more tables based on related columns.
Joins allow you to retrieve data from multiple tables in a single query, enabling you to work with data that is distributed across different tables.
Types of joins in MySQL:
INNER JOIN (or JOIN):
SELECT columns FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name;
Example:
SELECT employees.first_name, departments.department_name FROM employees INNER JOIN departments ON employees.department_id = departments.department_id;
LEFT JOIN (or LEFT OUTER JOIN):
SELECT columns FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name;
Example:
SELECT customers.customer_name, orders.order_date FROM customers LEFT JOIN orders ON customers.customer_id = orders.customer_id;
RIGHT JOIN (or RIGHT OUTER JOIN):
SELECT columns FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name;
Example:
SELECT orders.order_date, customers.customer_name FROM orders RIGHT JOIN customers ON orders.customer_id = customers.customer_id;
FULL OUTER JOIN (or FULL JOIN):
SELECT columns FROM table1 FULL JOIN table2 ON table1.column_name = table2.column_name;
Example:
SELECT employees.first_name, departments.department_name FROM employees FULL JOIN departments ON employees.department_id = departments.department_id;
SELF JOIN:
SELECT columns FROM table1 AS t1 JOIN table1 AS t2 ON t1.column_name = t2.column_name;
Example (for an employee hierarchy):
SELECT e1.employee_name, e2.manager_name FROM employees AS e1 JOIN employees AS e2 ON e1.manager_id = e2.employee_id;
Joins are powerful tools for combining data from multiple tables in MySQL.
Depending on your specific use case, you can choose the appropriate type of join to retrieve the desired data.