I have this problem. There are n tables created dynamically and each table has m columns, the columns could be repeated. This tables have in common 2 columns but there is no related data between them, for example: Table1 | A | B | Col1 | Col2 |
Table2
| A | B | Col3 | Col4 |
Table3
| A | B | Col1 | Col2 | Col4 |
What I want to do is to merge all the tables into a big one like this:
BigTable
| A | B | Col1 | Col2 | Col3 | Col4 |
And all the rows concatenated, for example if in table1 rows = 5, table2 rows = 3, table3 rows = 2, the big table will have 10 entries.
I can accomplish this by using a query like this:
SELECT A, B, Col1, Col2, null as Col3, null as Col4 FROM Table1
UNION
SELECT A, B, null as Col1, null as Col2, Col3, Col4 FROM Table2
UNION
SELECT A, B, Col1, Col2, null as Col3, Col4 FROM Table3
But I want to know if there is a better way to do this, because there will be more columns and more tables, and there is the possibility that all the columns are different.
The only improvement to your query is to use
union all
instead ofunion
. Only useunion
if you explicitly want to remove duplicates, because it always attempts to:EDIT:
You can further simplify this to:
The column names are only used for the first
select
in theunion all
. After that, the columns are identified by position.EDIT II:
There is a trick that you can use to get "logical" matches on
union all
. I don't particularly like it, but you don't have to list the columns for all the subqueries. However, theselect
is more complicated, and it has another subquery, and you still need subqueries:You can do this (using example tables to simplify),
table1
is,table2
is,Now perform the union,
Of course, you'll get empty values from columns
col4
andcol5
when the source row was fromtable1
, and empty values forcol1
andcol2
when the source row was fromtable2
.Substitute whatever default value you want for the empty values. My example uses the empty string, but you could also use
0
,null
, whatever.