简体   繁体   中英

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. It's much easier for me to illustrate with an example.

I have two tables:

Table 1

ColA  ColB  ColC
0     A     AL
1     B     DZ

Table 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.

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:

SELECT ColA, ColB, ColC
FROM Table1

UNION ALL

SELECT ColA, ColB, ColC
FROM Table2 

Note that UNION ALL working faster than 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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