1 difference
Both join and union can be used to merge data from one or more tables, the difference lies in the way the data is merged.
Simply put, join will merge data from other tables into a new column. Two tables (table A and table B) join to generate the same row of the table column data is a collection of table A and table B column data.
Union merges data from other tables into a new row. Two tables (table A and table B) The row data of the union generated table is a collection of table A and table B.
2 example
2.1 join
mysql> select * from roles;
+---------+------------+----------+
| role_id | occupation | camp |
+---------+------------+----------+
| 1 | warrior | alliance |
| 2 | paladin | alliance |
| 3 | rogue | Horde |
+---------+------------+----------+
3 rows in set (0.01 sec)
mysql>
mysql> select * from mount_info;
+----------+------------+---------+
| mount_id | mount_name | role_id |
+----------+------------+---------+
| 1 | horse | 1 |
| 2 | sheep | 1 |
| 3 | sheep | 4 |
+----------+------------+---------+
3 rows in set (0.01 sec)
————————————————
原文链接:https://blog.csdn.net/liitdar/article/details/80817087
Join table roles and table mount_info by role_id column , the result is:
mysql> SELECT a.role_id, a.occupation, a.camp, b.mount_name FROM roles a LEFT JOIN mount_info b ON a.role_id = b.role_id;
+---------+------------+----------+------------+
| role_id | occupation | camp | mount_name |
+---------+------------+----------+------------+
| 1 | warrior | alliance | horse |
| 1 | warrior | alliance | sheep |
| 2 | paladin | alliance | NULL |
| 3 | rogue | Horde | NULL |
+---------+------------+----------+------------+
4 rows in set (0.01 sec)
————————————————
原文链接:https://blog.csdn.net/liitdar/article/details/80817087
Join is generally used in conjunction with the on parameter, such as filtering from the merged results to obtain rows with the same specified column values in two tables. There are also inner join , left join and right join . For details, please refer to the referenced blog https://blog. csdn.net/liitdar/article/details/80817087 .
2.2 union
Refer to the example of this article:
https://www.w3school.com.cn/sql/sql_union.asp
Union is a prerequisite, that is, the columns of the two tables are the same.
The difference between union and union all is that the former will de-duplicate the merged result, so the latter will be faster.