MySQL LEFT, RIGHT JOIN tutorial mysql> SELECT buyers.
buyer_name,
MySQL joins are hard for beginners. At least for me when I was
buyers.quantity,
beginner.
products.product_name
I will try to explain the joins in the simplest possible way.
FROM buyers,products
WHERE buyers.pid=products.id;
Join in MySQL is a query where you can join one or more tables.
+------------+----------+--------------+
| buyer_name | quantity | product_name |
For example we have two tables: products and buyers with the +------------+----------+--------------+
following structures. | Steve | 2 | Shoes |
Table products: | John | 1 | Laptop |
| Larry | 1 | Monitor |
mysql> SELECT * FROM products; | Michael | 5 | Monitor |
+----+--------------+--------------+ +------------+----------+--------------+
| id | product_name | manufacturer | 4 rows in set (0.00 sec)
+----+--------------+--------------+
| 1 | Shoes | Company1 |
| 2 | Laptop | Company2 |
| 3 | Monitor | Company3 | Right Join
| 4 | DVD | Company4 |
+----+--------------+--------------+ mysql> SELECT buyer_name, quantity,
4 rows in set (0.00 sec) product_name
FROM buyers
Table buyers:
mysql> SELECT * FROM buyers; RIGHT JOIN products
ON buyers.pid=products.id;
+------------+----------+--------------+
+----+------+------------+----------+ | buyer_name | quantity | product_name |
| id | pid | buyer_name | quantity | +------------+----------+--------------+
+----+------+------------+----------+ | Steve | 2 | Shoes |
| 1 | 1 | Steve | 2 | | John | 1 | Laptop |
| 2 | 2 | John | 1 | | Larry | 1 | Monitor |
| 3 | 3 | Larry | 1 | | Michael | 5 | Monitor |
| 4 | 3 | Michael | 5 | | NULL | NULL | DVD |
| 5 | NULL | Steven | NULL | +------------+----------+--------------+
+----+------+------------+----------+ 5 rows in set (0.00 sec)
5 rows in set (0.00 sec)
What happens here is Mysql starts with the Right table (products). For
each id from the table products MySQL scans the left table - buyers to
find the matching pid. When it finds the matching pid it returns the
buyer_name and the quantity. For unmatched rows it returns null.
Left Join
mysql> SELECT buyer_name, quantity,
product_name FROM buyers
LEFT JOIN products
ON buyers.pid=products.id;
+------------+----------+--------------+
| buyer_name | quantity | product_name |
+------------+----------+--------------+
| Steve | 2 | Shoes |
| John | 1 | Laptop |
| Larry | 1 | Monitor |
| Michael | 5 | Monitor |
| Steven | NULL | NULL |
+------------+----------+--------------+
5 rows in set (0.00 sec)
What happened?
Mysql starts with the left table (buyers). For each row from the table
buyers mysql scans the table products, finds the id of the product and
returns the product name. Then the product name is joined with the
matching row from the table buyers. For unmatched rows it returns
null.
To make it simpler, the above query is same as (except the unmatched
rows are not returned):