For SQL Join, it may be confusing to learn. We know that SQL Join syntax has many inner, outer, and left. Sometimes, it is not very clear what the result set from Select looks like. There is an article on Coding Horror, through Venn diagram (Venn diagram, can be used to represent the logical relationship between multiple sets). SQL Join is explained. I find it clear and understandable, turn around.
Suppose we have two tables. Table A is the table on the left. Table B is the table on the right. Each of them has four records, two of which have the same name, as shown below: Let's see the difference between different JOINs
Form A | |
id | name |
1 | Pirate |
2 | Monkey |
3 | Ninja |
4 | Spaghetti |
Form B | |
id | name |
1 | Rutabaga |
2 | Pirate |
3 | Darth Vade |
4 | Ninja |
1.INNER JOIN
SELECT * FROM TableA INNER JOIN TableB ON TableA.name = TableB.name
result set | |||
(TableA.) | (TableB.) | ||
id | name | id | name |
1 | Pirate | 2 | Pirate |
3 | Ninja | 4 | Ninja |
The result set produced by Inner join is the intersection of A and B.
result set | |||
(TableA.) | (TableB.) | ||
id | name | id | name |
1 | Pirate | 2 | Pirate |
2 | Monkey | null | null |
3 | Ninja | 4 | Ninja |
4 | Spaghetti | null | null |
null | null | 1 | Rutabaga |
null | null | 3 | Darth Vade |
WHERE TableA.id IS null OR TableB.id IS null
result set | |||
(TableA.) | (TableB.) | ||
id | name | id | name |
2 | Monkey | null | null |
4 | Spaghetti | null | null |
null | null | 1 | Rutabaga |
null | null | 3 | Darth Vade |
result set | |||
(TableA.) | (TableB.) | ||
id | name | id | name |
1 | Pirate | 2 | Pirate |
2 | Monkey | null | null |
3 | Ninja | 4 | Ninja |
4 | Spaghetti | null | null |
result set | |||
(TableA.) | (TableB.) | ||
id | name | id | name |
2 | Monkey | null | null |
4 | Spaghetti | null | null |
Produces sets that are in table A but not in table B.
Note that the SELECT statement inside the UNION must have the same number of columns. Columns must also have similar data types. Also, the order of the columns in each SELECT statement must be the same. UNION selects only records, while UNION ALL lists all records.
new result set |
name |
Pirate |
Monkey |
Ninja |
Spaghetti |
Rutabaga |
Darth Vade |
new result set |
name |
Pirate |
Monkey |
Ninja |
Spaghetti |
Rutabaga |
Pirate |
Darth Vade |
Ninja |
list all
(3) Note:
new result set | |
id | name |
1 | Pirate |
2 | Monkey |
3 | Ninja |
4 | Spaghetti |
1 | Rutabaga |
2 | Pirate |
3 | Darth Vade |
4 | Ninja |
If there is a where, you can use:
SELECT column_list FROM t1 INNER JOIN t2 ON join_condition1 INNER JOIN t3 ON join_condition2 ... WHERE where_conditions;
More references:
PHP5: mysqli Insert, Query, Update and Delete Insert Update Delete Using mysqli (CRUD)
MySQL: Get a MySQL table structure with DESCRIBE
Three things you may need to know about MySQL LEFT JOIN
This article is transferred from: Mysql: Graphical difference between inner join, left join, right join, full outer join, union, union all