我稍微改变了你的数据模型:
SQL> create type school_t as object(
2 sid number(5,2),
3 name varchar(20))
4 /
Type created.
SQL> create type child_t as object(
2 cid number(5,2),
3 name varchar(20))
4 /
Type created.
SQL> create table school_tab of school_t
2 /
Table created.
SQL> create table child_tab of child_t
2 /
Table created.
SQL>
让我们填充嵌套表:
SQL> insert into child_tab
2 values (111, 'Fred')
3 /
1 row created.
SQL> insert into child_tab
2 values (112, 'Ayesha')
3 /
1 row created.
SQL> insert into child_tab
2 values (113, 'Aadil')
3 /
1 row created.
SQL> insert into school_tab
2 values (222, 'Bash Street')
3 /
1 row created.
SQL> insert into school_tab
2 values (223, 'Greyfriars')
3 /
1 row created.
SQL>
这是一个嵌套表:
SQL> create type school_child_t as object(
2 cid ref child_t,
3 sid ref school_t)
4 /
Type created.
SQL> create table school_child_tab of school_child_t
2 /
Table created.
SQL>
我们像这样填充交集表:
SQL> insert into school_child_tab
2 select cid, sid
3 from
4 ( select ref(c) as cid from child_tab c where c.cid = 111 )
5 , ( select ref(s) as sid from school_tab s where s.sid = 222 )
6 /
1 row created.
SQL> insert into school_child_tab
2 select cid, sid
3 from
4 ( select ref(c) as cid from child_tab c where c.cid = 112 )
5 , ( select ref(s) as sid from school_tab s where s.sid = 222 )
6 /
1 row created.
SQL> insert into school_child_tab
2 select cid, sid
3 from
4 ( select ref(c) as cid from child_tab c where c.cid = 113 )
5 , ( select ref(s) as sid from school_tab s where s.sid = 222 )
6 /
1 row created.
SQL> insert into school_child_tab
2 select cid, sid
3 from
4 ( select ref(c) as cid from child_tab c where c.cid = 113 )
5 , ( select ref(s) as sid from school_tab s where s.sid = 223 )
6 /
1 row created.
SQL>
查询返回结果
SQL> select c.name as child_name
2 , s.name as school_name
3 from school_child_tab sc
4 join child_tab c
5 on ( ref(c) = sc.cid )
6 join school_tab s
7 on ( ref(s) = sc.sid )
8 /
CHILD_NAME SCHOOL_NAME
-------------------- --------------------
Fred Bash Street
Ayesha Bash Street
Aadil Greyfriars
Aadil Bash Street
SQL>
当然,这提出了一个问题:如果要使用对象的 REF,是否需要 ID 列?当然,我认为对于 CHILD_T 类型有一个称为 NUMBER 类型的 CID 的属性和对于 SCHOOL_CHILD_T 类型具有相同名称但数据类型为 REF 的属性是一种误导。