JOIN和UNION的区别是什么?我能举个例子吗?


当前回答

加入:

连接用于显示具有相同或的列 不同表的不同名称。显示的输出 将单独显示所有列。也就是 列将彼此对齐。

联盟:

UNION集合操作符用于组合两个数据 具有相同数据类型的列的表。 当执行UNION时,来自两个表的数据将被删除 在具有相同数据类型的单列中收集。

例如:

请看下面两个表:

Table t1
Articleno article price manufacturer_id
1 hammer 3 $ 1
2 screwdriver 5 $ 2

Table t2
manufacturer_id manufacturer
1 ABC Gmbh
2 DEF Co KG

现在要执行JOIN类型,查询如下所示。

SELECT articleno, article, manufacturer
FROM t1 JOIN t2 ON (t1.manufacturer_id =
t2.manufacturer_id);

articelno article manufacturer
1 hammer ABC GmbH
2 screwdriver DEF Co KG

这是一个连接。

UNION意味着您必须将表或结果集与 相同数量和类型的列,然后加上这个 表/结果集在一起。看看这个例子:

Table year2006
Articleno article price manufacturer_id
1 hammer 3 $ 1
2 screwdriver 5 $ 2

Table year2007
Articleno article price manufacturer_id
1 hammer 6 $ 3
2 screwdriver 7 $ 4

SELECT articleno, article, price, manufactruer_id
FROM year2006
UNION
SELECT articleno, article, price, manufacturer_id
FROM year2007

articleno article price manufacturer_id
1 hammer 3 $ 1
2 screwdriver 5 $ 2
1 hammer 6 $ 3
2 screwdriver 7 $ 4

其他回答

Union使两个查询看起来像一个查询。连接用于在单个查询语句中检查两个或多个表

UNION将来自查询的行依次排列,而JOIN生成笛卡尔积并对其进行子集——这是完全不同的操作。UNION的简单例子:

mysql> SELECT 23 AS bah
    -> UNION
    -> SELECT 45 AS bah;
+-----+
| bah |
+-----+
|  23 | 
|  45 | 
+-----+
2 rows in set (0.00 sec)

类似的JOIN的简单例子:

mysql> SELECT * FROM 
    -> (SELECT 23 AS bah) AS foo 
    -> JOIN 
    -> (SELECT 45 AS bah) AS bar
    -> ON (33=33);
+-----+-----+
| foo | bar |
+-----+-----+
|  23 |  45 | 
+-----+-----+
1 row in set (0.01 sec)

我喜欢把一般的区别想成:

join连接表 UNION (et all)组合查询。

UNION将两个或多个查询的结果组合成一个结果集,该结果集包含属于联合中所有查询的所有行。

通过使用join,可以根据表之间的逻辑关系从两个或多个表中检索数据。联接指示SQL应该如何使用一个表中的数据来选择另一个表中的行。

UNION操作不同于使用join来组合两个表中的列。

联盟的例子:

SELECT 1 AS [Column1], 2 AS [Column2]
UNION
SELECT 3 AS [Column1], 4 AS [Column2]

输出:

Column1    Column2
-------------------
1          2
3          4

加入的例子:

SELECT a.Column1, b.Column2 FROM TableA a INNER JOIN TableB b ON a.Id = b.AFKId

这将输出这两个表中条件a.Id = b.AFKId为真的所有行。

记住,union将合并结果(SQL Server)(特性或错误?)

select 1 as id, 3 as value
union
select 1 as id, 3 as value

id,值

1,3

select * from (select 1 as id, 3 as value) t1 inner join (select 1 as id, 3 as value) t2 on t1.id = t2.id

id值,id值

1,3,1,3