SQL Joins
Differense between SQL JOINs is the most popular question on enterview. So create Table a is on the left, and Table b is on the right.
Create tables
+------++------+ | a || b | +------++------+ | 1 || 1 | | 2 || 2 | | NULL || NULL | | 10 || 20 | +------++------+
Sql query:
INNER JOIN AND STRAIGHT_JOIN
The INNER JOIN keyword selects all rows from both tables. INNER JOIN is the same as JOIN.
A STRAIGHT_JOIN identifies and combines matching rows which are stored in two related tables. This is what an inner join also does. The difference between an inner join and a straight join is that a straight join forces MySQL to read the left table first.
![]
+------+------+ | a | b | +------+------+ | 1 | 1 | | 2 | 2 | +------+------+
Without condition ON we make CROSS JOIN
OR
![][1]
+------+------+
| b | a |
+------+------+
| 1 | 1 |
| 2 | 1 |
| NULL | 1 |
| 20 | 1 |
| 1 | 2 |
| 2 | 2 |
| NULL | 2 |
| 20 | 2 |
| 1 | NULL |
| 2 | NULL |
| NULL | NULL |
| 20 | NULL |
| 1 | 10 |
| 2 | 10 |
| NULL | 10 |
| 20 | 10 |
+------+------+ #### LEFT JOIN == LEFT ~~OUTER~~ JOIN
The LEFT JOIN keyword returns all rows from the left table (A), with the matching rows in the right table (B). The result is NULL in the right side when there is no match.
![][2]
+------+------+ | a | b | +------+------+ | 1 | 1 | | 2 | 2 | | NULL | NULL | | 10 | NULL | +------+------+
If add WHERE condition:
![][3]
+------+------+ | a | b | +------+------+ | NULL | NULL | | 10 | NULL | +------+------+
RIGHT JOIN = RIGHT OUTER JOIN
The RIGHT JOIN keyword returns all rows from the right table (B), with the matching rows in the left table (A). The result is NULL in the left side when there is no match.
![][4]
+------+------+ | a | b | +------+------+ | 1 | 1 | | 2 | 2 | | NULL | NULL | | NULL | 20 | +------+------+
![][5]
+------+------+ | a | b | +------+------+ | NULL | NULL | | NULL | 20 | +------+------+
FULL OUTER
The FULL OUTER JOIN keyword returns all rows from the left table (A) and from the right table (B). The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins.
MYSQL don’t have FULL JOINS, but can sure [emulate] them.
![][6]
+------+------+ | a | b | +------+------+ | 1 | 1 | | 2 | 2 | | NULL | NULL | | 10 | NULL | | NULL | 20 | +------+------+
For MYSQL:
![][7]
+------+------+ | a | b | +------+------+ | NULL | NULL | | 10 | NULL | | NULL | 20 | +------+------+
[]: ../../../../assets/img/posts/2015/02/join1.png [1]: ../../../../assets/img/posts/2015/02/join8.png [2]: ../../../../assets/img/posts/2015/02/join2.png [3]: ../../../../assets/img/posts/2015/02/join3.png [4]: ../../../../assets/img/posts/2015/02/join4.png [5]: ../../../../assets/img/posts/2015/02/join5.png [emulate]: http://dev.mysql.com/doc/refman/5.0/en/outer-join-simplification.html [6]: ../../../../assets/img/posts/2015/02/join6.png [7]: ../../../../assets/img/posts/2015/02/join7.png