Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine more than 2 Microsoft Access tables into one table?

Let's say I have 10 tables, each tableN has an ID and a ValueN. I want to combine all of them into one table which has the following content:

ID Value1 Value2 Value3 ...

The IDs are unique but each table can have any number of records, so a result row can be:

001 3.1 Null 4.6 ...

I know how to do this simple query when there are only 2 tables. But don't know the best way to compare the ID values from 10 tables.

like image 501
RJIGO Avatar asked Nov 15 '25 02:11

RJIGO


1 Answers

Say you have 3 tables (or any number of tables)

Table1:          Table2:           Table3
ID  Value1       ID   Value2       ID   Value3
1   A            1    AAA          1    111
2   B            2    BBB          2    222
3   C            5    EEE          3    333
                                   4    444
                                   5    555

You can use a query like this to make sure that you get all possible data from all tables:

SELECT U.ID,
       Table1.Value1,
       Table2.Value2,
       Table3.Value3
FROM   (((SELECT ID FROM Table1
          UNION
          SELECT ID FROM Table2
          UNION
          SELECT ID FROM Table3) AS U
         LEFT JOIN Table1 ON U.ID=Table1.ID)
        LEFT JOIN Table2 ON U.ID=Table2.ID)
       LEFT JOIN Table3 ON U.ID=Table3.ID; 

The result of which is:

ID    Value1    Value2     Value3
1     A         AAA        111
2     B         BBB        222
3     C                    333
4                          444
5               EEE        555    

Basically, it's just a succession of LEFT JOIN on each table, all joined by the union of all possible IDs accross all tables:

SELECT ID FROM Table1
UNION
SELECT ID FROM Table2
UNION
SELECT ID FROM Table3
like image 156
Renaud Bompuis Avatar answered Nov 17 '25 20:11

Renaud Bompuis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!