1 區別
join 和 union 都可以被用來合併一張或多張表的數據,區別在於合併數據的方式。
簡單來說,join 會將其他表的數據合併到新的列。兩張表(表A和表B) join 生成表的同一行的列數據是表A與表B列數據的集合。
union 將其他表的數據合併到新的行。兩張表(表A和表B) union 生成表的行數據是表A與表B行數據的集合。
2 例子
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
按 role_id 列 join 表roles和表mount_info,結果爲:
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 一般會結合 on 參數使用,比如從合併結果中過濾得到兩張表指定列值相同的行, 另外有 inner join, left join 和 right join,具體可參考引用的這篇博客https://blog.csdn.net/liitdar/article/details/80817087。
2.2 union
參考這篇文章的例子:
https://www.w3school.com.cn/sql/sql_union.asp
union 是前提條件的,那就是兩張表的列一樣。
union 和 union all 的區別是前者會將合併後的結果去重,因此後者速度會更快。