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 的区别是前者会将合并后的结果去重,因此后者速度会更快。