sql中 join 和 union區別

1 區別

joinunion 都可以被用來合併一張或多張表的數據,區別在於合併數據的方式。

簡單來說,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 joinleft joinright join,具體可參考引用的這篇博客https://blog.csdn.net/liitdar/article/details/80817087

2.2 union

參考這篇文章的例子:
https://www.w3school.com.cn/sql/sql_union.asp

union 是前提條件的,那就是兩張表的列一樣。

unionunion all 的區別是前者會將合併後的結果去重,因此後者速度會更快。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章