I have 2 Oracle tables
table_1:
ID target_id name url
1 A John example.org
2 B Jane helloworld.com
table_2:
id1 target_id col1 col2
X A aaa bbb
Y A ccc ddd
I am trying to run query joining table_1 and table_2 with target_id, and get JSON similar to followings (using Java)
[{"id": 1, "name"="John", "url": "example.org",
"target": [{"id1":"X", "col1": ...}, {"id1":"Y", "col1": ...}]
},
{"id": 2, "name"="Jane", "url": "helloworld.com"}]
What we are doing right now is to iterate table_1, for each row, select from table_2, and add object into a list, and at the end serilize it to JSON.
Is that a better way instead of making nested sql in the loop in Oracle?
2
Answers
table1:table2 = 1:N ?
Use
JSON_ARRAYAGG
andJSON_OBJECT
:Which, for the sample data:
Outputs:
fiddle