Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine multiple tables that vary slightly in columns

Tags:

sql

join

union

I have multiple tables where there are roughly 10 common columns, but some tables have 1-2 extra columns.

I would like to combine all these tables into one table with a row for each row from each table, with NULL values for any columns that didn't exist in each particular row's source table.

So my inputs look roughly like this:

table1
id  |  colA  | colB

table2
id  |  colA  | colB  | colC

table3
id  |  colA  | colB  | colD

And I am trying to get this:

allTables
id  |  colA  | colB  | colC | colD

In the above example all rows from table1 would have NULL values for colC and colD in allTables, all rows from table2 would have null values for colD, and all rows from table3 would have null values in colC.

A couple notes:

  • The column id is not the same or related between tables in any way
  • My example shows 3 tables, but I have about 8-9.
  • Duplicate rows exist within each source table and should be preserved.

In particular I'm interested if there's an answer similar to the top voted one here or something like it that's more generalized.

like image 778
mindless.panda Avatar asked Jul 19 '11 17:07

mindless.panda


1 Answers

SELECT
    id,
    colA,
    colB,
    NULL AS colC,
    NULL AS colD
FROM
    Table1
UNION ALL
SELECT
    id,
    colA,
    colB,
    colC,
    NULL AS colD
FROM
    Table2
UNION ALL
SELECT
    id,
    colA,
    colB,
    NULL AS colC,
    colD
FROM
    Table3

Since the ids are not related, you might also want to track which table the row came from in case there are duplicates between the tables. To do that, just have a hard-coded value with an alias with a different value in each of the three SELECT statements.

like image 96
Tom H Avatar answered Nov 14 '22 21:11

Tom H