What is the concept of joins in MySQL?



In MySQL, a "join" is a database operation that combines rows from two or more tables based on a related column between them. Joins are used to retrieve data from multiple tables by specifying how the tables are related and how the data should be combined.

There are several types of joins in MySQL:


INNER JOIN:

Explanation:   Returns only the matching rows from both tables.
 
Syntax:
SELECT columns FROM table1 INNER JOIN table2 ON table1.column = table2.column;

Example:

SELECT orders.order_id, customers.customer_name FROM orders INNER JOIN customers ON orders.customer_id = customers.customer_id;

LEFT JOIN (LEFT OUTER JOIN):

Explanation: Returns all rows from the left table and matching rows from the right table.
 
Syntax:

SELECT columns FROM table1 LEFT JOIN table2 ON table1.column = table2.column;

Example:

SELECT customers.customer_name, orders.order_id FROM customers LEFT JOIN orders ON customers.customer_id = orders.customer_id;

RIGHT JOIN (RIGHT OUTER JOIN):

Explanation: Returns all rows from the right table and matching rows from the left table.
 
Syntax:

SELECT columns FROM table1 RIGHT JOIN table2 ON table1.column = table2.column;

Example:

SELECT orders.order_id, customers.customer_name FROM orders RIGHT JOIN customers ON orders.customer_id = customers.customer_id;

FULL JOIN (FULL OUTER JOIN):

Explanation: Returns all rows from both tables along with matching rows.
 
Syntax:

SELECT columns FROM table1 FULL JOIN table2 ON table1.column = table2.column;

Example:

SELECT customers.customer_name, orders.order_id FROM customers FULL JOIN orders ON customers.customer_id = orders.customer_id;

CROSS JOIN:

Explanation: Produces a Cartesian product of both tables.
Syntax:

SELECT  columns  FROM   table1   CROSS JOIN   table2;

Example:

SELECT employees.employee_name, departments.department_name FROM employees CROSS JOIN departments;

SELF JOIN:


Explanation: Joins a table with itself.
Syntax:

SELECT columns FROM table1 AS t1 INNER JOIN table1 AS t2 ON t1.column = t2.column;

Example:

SELECT e1.employee_name, e2.manager_name FROM employees AS e1 INNER JOIN employees AS e2 ON e1.manager_id = e2.employee_id;

Comments

Popular posts from this blog

Installing MySQL and MySQL Workbench

Java Program to Check Palindrome Number

Scenario : 1