3

是否可以直接选择分层用户类型?

想象一下这样的表结构:

PARENT
------
ID
NAME

CHILD
-----
ID
PARENT_ID
NAME

此外,我有这样的用户类型:

create or replace type child_item as object
(
  ID NUMBER(10),
  NAME VARCHAR(255)
);

create or replace type children_table as table of child_item;

create or replace type parent_item as object
(
  ID NUMBER(10),
  NAME VARCHAR(255),
  CHILDREN CHILDREN_TABLE
);

create or replace type parent_table as table of parent_item;

还有这样的声明:

select * from parent p inner join child c on p.id = c.parent_id;

现在,我希望该语句的结果位于 type 的对象中parent_tableFOR如果不使用复杂的循环,这是否可能?

4

2 回答 2

4

您可以使用COLLECT

SELECT parent_item(p.ID, 
                   p.NAME, 
                   CAST(COLLECT(child_item(c.id, c.NAME)) AS children_table))
  FROM PARENT p
 INNER JOIN child c ON p.id = c.parent_id
 GROUP BY p.ID, p.NAME

这将返回一个列表PARENT_ITEM,您可以将其批量收集到PARENT_TABLE.

您可以在外部查询中再次使用 COLLECT 来直接获取 PARENT_TABLE:

SELECT CAST(COLLECT(parents) AS parent_table)
  FROM (SELECT parent_item(p.ID, 
                           p.NAME, 
                           CAST(COLLECT(child_item(c.id, c.NAME)) 
                             AS children_table)
                          ) parents
          FROM PARENT p
         INNER JOIN child c ON p.id = c.parent_id
         GROUP BY p.ID, p.NAME)
于 2012-05-09T13:03:22.357 回答
1

使用CAST(MULTISET())

with data as (
select p.id pid,p.name pname,cast(multiset(select c.id,c.name 
from child c where c.parent_id=p.id) AS children_table) ct
from parent p
)
select cast(multiset(select pid,pname,ct from data) as parent_table) 
from dual;
于 2012-05-09T12:43:29.917 回答