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将合并结果(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

UNION操作符只是用于组合两个或多个SELECT语句。

而JOIN用于从每个表中选择行,可以通过内、外、左或右方法。

参考这里和这里。用例子来解释会更好。

加入:

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

联盟:

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

你可能会看到对两者相同的解释,但这完全令人困惑。

联盟:

加入: