使用分层JSON的Oracle 19C查询

v8wbuo2f  于 2023-08-04  发布在  Oracle
关注(0)|答案(2)|浏览(121)

我有2个Oracle表

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

字符串
我试图运行查询连接table_1和table_2与target_id,并获得类似于以下的JSON(使用Java)

[{"id": 1, "name"="John", "url": "example.org", 
"target": [{"id1":"X", "col1": ...}, {"id1":"Y", "col1": ...}]
}, 
{"id": 2, "name"="Jane", "url": "helloworld.com"}]


我们现在做的是迭代table_1,对于每一行,从table_2中选择,并将对象添加到列表中,最后将其序列化为JSON。
这是不是一个更好的方法,而不是在Oracle中的循环嵌套SQL?

xzabzqsa

xzabzqsa1#

使用JSON_ARRAYAGGJSON_OBJECT

SELECT JSON_ARRAYAGG(
         JSON_OBJECT(
           KEY 'id'     VALUE t1.id,
           KEY 'name'   VALUE t1.name,
           KEY 'url'    VALUE t1.url,
           KEY 'target' VALUE t2.target ABSENT ON NULL
         )
       ) AS data
FROM   table_1 t1
       LEFT OUTER JOIN (
         SELECT target_id,
                JSON_ARRAYAGG(
                  JSON_OBJECT(
                    KEY 'id1' VALUE id1,
                    KEY 'col1' VALUE col1,
                    KEY 'col2' VALUE col2
                  )
                ) AS target
         FROM   table_2
         GROUP BY target_id
       ) t2
       ON t1.target_id = t2.target_id

字符串
其中,对于样本数据:

CREATE  TABLE table_1 (ID, target_id, name, url) AS
SELECT 1, 'A', 'John', 'example.org' FROM DUAL UNION ALL
SELECT 2, 'B', 'Jane', 'helloworld.com' FROM DUAL;

CREATE  TABLE table_2 (id1, target_id, col1, col2) AS
SELECT 'X', 'A', 'aaa', 'bbb' FROM DUAL UNION ALL
SELECT 'Y', 'A', 'ccc', 'ddd' FROM DUAL;


输出:
| DATA |
| ------------ |
| [{"id":1,"name":"John","url":"example.org ","target":[{"id1":"X","col1":"aaa","col2":"bbb"},{"id1":"Y","col1":"ccc","col2":"ddd"}]},{"id":2,"name":"Jane","url":"helloworld.com "}] |
fiddle

polkgigr

polkgigr2#

table1:table2 = 1:N?

SELECT AA.*, BB.* FROM table_1 AA
LEFT JOIN table_2 BB ON AA.target_id=BB.target_id
ORDER BY AA.id

字符串

相关问题