oracle 使用子查询并将多个列连接到JSON对象中

3bygqnnd  于 2023-04-20  发布在  Oracle
关注(0)|答案(1)|浏览(145)

上下文

使用DBeaver / Oracle,我试图匹配一个Parent表,并显示返回与该父表相关的所有子表作为一个列值。

示例数据

--Parent Table--
ID    NAME    GENDER
1     John    M
2     Ruby    F

--Child Table--
REL_ID    NAME    GENDER   AGE
1         Lucy    F        10
1         George  M        9
2         Angie   F        14

**REL_ID = ID

预期结果

ID    NAME    CHILD
1     John    [{"REL_ID": 1, "NAME": "Lucy", "AGE": "10"}, {"ID": 1, "NAME": "George", "AGE": "9"}]
2     RUBY    [{"REL_ID": 2, "NAME": "ANGIE", "AGE": "14"}]
ldioqlga

ldioqlga1#

您可以使用相关子查询和JSON函数:

SELECT id,
       name,
       ( SELECT JSON_ARRAYAGG(
                  JSON_OBJECT(
                    KEY 'REL_ID' VALUE c.rel_id,
                    KEY 'NAME'   VALUE c.name,
                    KEY 'AGE'    VALUE c.age
                  )
                )
         FROM   child c
         WHERE  c.rel_id = p.id
       ) AS child
FROM   parent p

其中,对于样本数据(由@ PonderStibons提供):

create table parent(ID, NAME, GENDER) as
  select 1, 'John', 'M' from dual union all
  select 2, 'Ruby', 'F' from dual;

create table child(REL_ID, NAME, GENDER, AGE) as
  select 1, 'Lucy', 'F', 10 from dual union all
  select 1, 'George', 'M', 9 from dual union all
  select 2, 'Angie', 'F', 14 from dual;

输出:
| ID|名称|儿童|
| --------------|--------------|--------------|
| 1|约翰|[{“REL_ID”:1,“NAME”:“Lucy”,“AGE”:10},{“REL_ID”:1,“NAME”:“乔治”,“AGE”:9}]|
| 二|Ruby|[{“REL_ID”:2,“NAME”:“Angie”,“AGE”:14}]|
fiddle

相关问题