I have a query where I need to join a large number of tables on a single column, where records should be joined when any records from any tables match on that column. An example:
A
----------
id | a_value
----------
1 | foo
2 | bar
B
----------
id | b_value
----------
2 | cad
3 | qud
C
----------
id | c_value
----------
1 | fiz
4 | buz
D
----------
id | d_value
----------
5 | sas
6 | tos
SELECT id, a_value, b_value, c_value, d_value FROM <join A, B, C, D by id>
should return a result set like this:
results
------------------------------------------
id | a_value | b_value | c_value | d_value
------------------------------------------
1 | foo | null | fiz | null
2 | bar | cad | null | null
3 | null | qud | null | null
4 | null | null | buz | null
5 | null | null | null | sas
6 | null | null | null | tos
You could write the joins like this:
A FULL JOIN B ON A.id = B.id
FULL JOIN C ON A.id = C.id OR B.id = C.id
FULL JOIN D ON A.id = D.id OR B.id = D.id OR C.id = D.id
but that seems absurd, and would grow out of control rapidly as the number of columns increases (joining n tables in this manner requires n*(n-1)/2 conditions). There ahs to be a better way. Does anyone have any ideas?