MySQL Joins
used to combine rows from two or more tables, based on a related column between them. There are different types of joins that you can use depending on how you want to combine the data.
Types of Joins
- INNER JOIN: Returns records that have matching values in both tables
- LEFT JOIN: Returns all records from the left table, and the matched records from the right table
- RIGHT JOIN: Returns all records from the right table, and the matched records from the left table
- CROSS JOIN: Returns all records from both tables
INNER JOIN
The INNER JOIN returns only the rows where there is a match in both tables.
If there is no match, those rows are excluded from the result set.
SELECT column_name(s) FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name;LEFT JOIN
The LEFT JOIN returns all rows from the left table (the first table), and the matching rows from the right table (the second table).
If there is no match, NULL values are returned for columns from the right table.
SELECT columns FROM table1 LEFT JOIN table2 ON table1.column = table2.column;RIGHT JOIN
The RIGHT JOIN is the opposite of the LEFT JOIN.
It returns all rows from the right table, and the matching rows from the left table.
If there is no match, NULL values are returned for columns from the left table.
SELECT columns FROM table1 RIGHT JOIN table2 ON table1.column = table2.column;CROSS JOIN
The CROSS JOIN keyword returns all records from both tables (table1 and table2).
SELECT column_name(s) FROM table1 CROSS JOIN table2;SELF JOIN
A SELF JOIN is when a table is joined with itself.
SELECT * FROM table_name AS t1 JOIN table_name AS t2 ON t1.column_name = t2.column_name;