mysql> SELECT u.name,o.items FROM users as u RIGHT JOIN orders as o ON u.id=o.uid ;
+——+——–+
| name | items |
+——+——–+
| AAAA | Pen |
| BBBB | Watch |
| CCCC | shoe |
| DDDD | mobile |
+——+——–+
4 rows in set (0.00 sec)
mysql> SELECT u.name,o.items FROM users as u LEFT JOIN orders as o ON u.id=o.uid ;
+——+——–+
| name | items |
+——+——–+
| AAAA | Pen |
| BBBB | Watch |
| CCCC | shoe |
| DDDD | mobile |
| EEEE | NULL |
+——+——–+
5 rows in set (0.01 sec)
mysql> SELECT u.name,o.items FROM users as u INNER JOIN orders as o ON u.id=o.uid ;
+——+——–+
| name | items |
+——+——–+
| AAAA | Pen |
| BBBB | Watch |
| CCCC | shoe |
| DDDD | mobile |
+——+——–+
4 rows in set (0.00 sec)
SQL JOIN can be used to fetch data from more than one tables based the relationship between columns in tables . Tables are usually related each with primary keys . primary key can be a column with unique value in it .
There are mainly 4 SQL JOINs
JOIN: Return rows when there is at least one match in both tables
LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
FULL JOIN: Return rows when there is a match in one of the tables