简体   繁体   English

合并SQL中相同表的列

[英]Merging columns from identical tables in SQL

I'm having difficulty finding a solution to this problem, as searching for merging SQL columns or adding columns from table gives a wide variety of results I don't want. 我很难找到解决这个问题的方法,因为搜索合并SQL列或从表中添加列会产生我不想要的各种结果。 It's much easier for me to illustrate with an example. 用一个例子说明我就容易多了。

I have two tables: 我有两张桌子:

Table 1 表格1

ColA  ColB  ColC
0     A     AL
1     B     DZ

Table 2 表2

ColA  ColB  ColC
2     C     IS
3     D     KA

I want to merge these tables so the similar columns are basically combined, so I've got a new table with the same structure, and all of the values. 我想合并这些表,因此类似的列基本上是组合在一起的,所以我有一个具有相同结构和所有值的新表。 So the output would be: 所以输出将是:

Output 产量

ColA  ColB  ColC
0     A     AL
1     B     DZ
2     C     IS
3     D     KA

The issue is I want to find the distinct values across these columns from two similarly structured tables, so I cannot see how I can use a join for this, as if I join on any one value the other values will be lost, and a multiple-field join doesn't seem to work. 问题是我想从两个结构相似的表中找到这些列的不同值,所以我看不出如何使用连接,就好像我加入任何一个值,其他值将丢失,以及多个-field join似乎不起作用。

If you want to keep duplicate rows you could use UNION ALL and if you want to remove duplicate rows from result set you could use UNION in following: 如果要保留重复的行,可以使用UNION ALL ,如果要从结果集中删除重复的行,可以在下面使用UNION

SELECT ColA, ColB, ColC
FROM Table1

UNION ALL

SELECT ColA, ColB, ColC
FROM Table2 

Note that UNION ALL working faster than UNION 请注意, UNION ALL工作速度比UNION

select ColA, ColB, ColC from table1
union 
select ColA, ColB, ColC from table2 

The union operator allows you to place the result of one query after the other, and eliminates duplicates: union运算符允许您将一个查询的结果放在另一个查询之后,并消除重复:

SELECT cola, colb, colc
FROM   table1
UNION
SELECT cola, colb, colc
FROM   table2
select ColA, ColB, ColC from table1
union 
select ColA, ColB, ColC from table2 

You can also use UNION ALL 您也可以使用UNION ALL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM