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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With