从嵌套的引用表中选择查询

时间:2017-03-18 12:26:11

标签: sql oracle user-defined-types nested-table object-relational-model

我有两个对象关系表:person_tableaccount_table,由对象personaccount构建。 帐户行包含共享此帐户的所有人的嵌套表格,其类型为' customer_list'。

create type person as object(
  id integer,
  name varchar2,
  phone varchar2
);


create type customer_list as table of ref person;

create type account as object(
  accid integer,
  owned_by customer_list,
  balance Integer
);

create table account_table of account;

create table person_table of person;

我想根据个人的身份选择特定人拥有的所有帐户。如何浏览所有嵌套的帐户表,查询是什么?我尝试了不成功的查询。

例如

select a.*
from account_table a
where table(a.owned_by) = (select ref(p) from person_table p where p.id=id_given);

谢谢

1 个答案:

答案 0 :(得分:1)

这是我的测试数据:

SQL> select * from person_table;

        ID NAME                           PHONE
---------- ------------------------------ ------------
        11 MR KNOX                        07000700811
        22 SAM-I-AM                       07000700822

SQL> select * from account_table;

     ACCID
----------
OWNED_BY
--------------------------------------------------------------------------------
   BALANCE
----------
       123
CUSTOMER_LIST(00002202084B026AE209637509E050007F010047FD4B026AE209627509E050007F010047FD
            , 00002202084B026AE209647509E050007F010047FD4B026AE209627509E050007F010047FD)
      9900

       345
CUSTOMER_LIST(00002202084B026AE209637509E050007F010047FD4B026AE209627509E050007F010047FD)
        30


SQL>

Sam-I-Am和Knox先生是第一个账户的共同所有人,诺克斯先生是第二个账户的唯一所有者。要查找Mr Knox拥有的帐户,我们可以运行此查询,从person_table查找REF ...

SQL> select acct.accid
  2        , acct.balance
  3        , deref(value(ob)).name as owned_by
  4        , deref(value(ob)).phone as ntact_noco
  5  from account_table acct
  6       cross join table(acct.owned_by) ob
  7  where ob.column_value = ( select ref(p) pref
  8                            from person_table p
  9                            where p.name = 'MR KNOX')
 10  /  

     ACCID    BALANCE OWNED_BY                       NTACT_NOCO
---------- ---------- ------------------------------ ------------
       123       9900 MR KNOX                        07000700811
       345         30 MR KNOX                        07000700811

SQL> 

或者,我们可以使用DEREF语法查找此人:

SQL> select acct.accid
  2         , acct.balance
  3         , deref(value(ob)).name as owned_by
  4         , deref(value(ob)).phone as contact_no
  5  from account_table acct
  6       cross join table(acct.owned_by) ob
  7  where  deref(value(ob)).id = 11 
  8  /

     ACCID    BALANCE OWNED_BY                       CONTACT_NO
---------- ---------- ------------------------------ ------------
       123       9900 MR KNOX                        07000700811
       345         30 MR KNOX                        07000700811

SQL>