I try to write a SQL query (using full outer join) that creates a full result set from three tables that are related to each other by n:m-relationships.
The initial situation is a normalized data model with three entities: person, artifact and location. Each of the entities are related to every other entity via a n:m-relationship which is represented by intersection tables.
person { person_id, ... }
artifact { artifact_id, ... }
location { location_id, ... }
rel_person_artifact { person_id, artifact_id, role_id }
rel_person_location { person_id, location_id, role_id }
rel_artifact_location { artifact_id, location_id, role_id }
My goal is to create a result set from all three tables that contains all persons, artifacts and locations.
To solve the problem I tried the following statement:
select
*
from
person per
full outer join rel_person_artifact rpa on per.person_id = rpa.person_id
full outer join artifact art on art.artifact_id = rpa.artifact_id
full outer join rel_artifact_location ral on ral.artifact_id = art.artifact_id
full outer join location loc on loc.location_id = ral.location_id
full outer join rel_person_location rpl on rpl.person_id = per.person_id;
This query is syntatically correct but is returns worng content because the join handles one table after the other. At the end of the day not every relationship is represented in the result set.
Is there any way to combine the above tables in order to get a complete and correct result set?
EDIT. Here are some sample records (I stick to the intersection tables):
rel_person_artifact ( 'Peter', 'car 1', 'owner' ), ( 'Alex', 'car 1', 'driver' )
rel_person_location ( 'Peter', 'location 1', 'home' ), ( 'Paul', 'location 2', 'place of work' )
rel_artifact_location ( 'car 1', 'location 1', 'parking' )
Of course the data can be much more complex than this example. As mentioned in a comment below there might also be circual relationships.
I'm not sure how a result set should look like, i'm not even sure weather this combination is possible at all?
Thank you very much!
Regards