I have a simple data structure of 2 tables. First table holds json documents
CREATE TABLE public."TableData" (
dataid integer,
tableid integer,
data jsonb,
"addedOn" date,
ownerid integer,
)
Here is sample of test json data in table
dataid data
1 "{"email": "lbush@gmail.com", "items": {"qty": 24, "product": "Diaper"}, "lastname": "Bush", "firstname": "Lily"}" "2019-10-29" 1
5 "{"city": "Boston", "state": "MA", "rating": 1, "school": "Harvard"}
12 "{"major": "English", "credits": 350, "field of study": "Aerospace Engineering"}"
The second table is used to join documents together. The TableData.dataid connects to "left_id" or "right_id" depending on the connection.
CREATE TABLE public.relations (
relationid integer
left_id integer,
right_id integer,
"addedOn" date,
ownerid integer
)
here is 2 rows that connect the 3 documents
relationid left_id _right_id
1 1 5
2 5 12
I am looking for the right query syntax that lets me connect any hierarchy of documents together such that I can query/filter and have the output show correctly. For example, here is a query that works when just linking the first two documents together.
SELECT Contact.data -> 'firstname' as firstname,School.data -> 'school' as schoolname
from "public"."relations" as connections
left join "public"."TableData" as Contact
on Contact.dataid = connections.left_id
left join "public"."TableData" as School
on School.dataid = connections.right_id
This correctly outputs:
firstname schoolname
"Lily" "Harvard"
But, how do I now extend this to include additional connections? I tried the following to link the 3rd document, but not getting correct output.
SELECT Contact.data -> 'firstname' as firstname,
School.data -> 'school' as schoolname,
Major.data -> 'major' as majorname
from "public"."relations" as connections
left join "public"."TableData" as Contact
on Contact.dataid = connections.left_id
left join "public"."TableData" as School
on School.dataid = connections.right_id
left join "public"."TableData" as Major
on major.dataid = connections.right_id
left join "public"."TableData"
on School.dataid = connections.left_id
here is incorrect output:
firstname schoolname major
"Lily" "Harvard"
null null "Aerospace Enginering"
What I want/am looking for is:
firstname schoolname major
"Lily" "Harvard" "Aerspace Engineering"
How do I string multiple joins to the "Relations" table in order to get this output??