如何在oracle中实现多值属性?

时间:2010-06-11 19:28:57

标签: sql oracle plsql

我想在表格的电子邮件ID列中存储多个电子邮件ID,作为多值属性。我怎样才能在oracle中做到这一点?

2 个答案:

答案 0 :(得分:3)

执行此操作的传统关系方式是使用子堆表:

create table emails 
    (id number
     , email_address varchar2(254)
     , constraint em_t23_fk foreign key (id)
                  references t23 (id)
                  )
/

但是,你暗示了一个嵌套表:

create type email_t as object
    (email_address varchar2(254))
/

create type email_nt as table of email_t
/
alter table t23
    add emails email_nt
    nested table emails store as emails_table
/

以下是它的工作原理:

SQL> update t23
  2  set emails = email_nt (email_t('sam_i_am@example.com')
  3                          , email_t('green_eggs_n_ham@yahoo.co.uk'))
  4  where id = 222
  5  /

1 row updated.

SQL> select * from t23
  2  where id = 222
  3  /

        ID NAME                           DOB
---------- ------------------------------ ---------
EMAILS(EMAIL_ADDRESS)
----------------------------------------------------------------------------------
       222 Sam-I-Am                       06-AUG-02
EMAIL_NT(EMAIL_T('sam_i_am@example.com'), EMAIL_T('green_eggs_n_ham@yahoo.co.uk'))


SQL>

修改

VARRAY的解决方案基本相同:

SQL> alter table t23
  2      drop column emails
  3  /

Table altered.

SQL> create type email_va as varray(5) of varchar2(254)
  2  /

Type created.

SQL> alter table t23
  2      add emails email_va
  3  /

Table altered.

SQL> update t23
  2  set emails = email_va ('sam_i_am@example.com'
  3                        , 'green_eggs_n_ham@yahoo.co.uk')
  4  where id = 222
  5  /

1 row updated.

SQL> select t23.name
  2         , e.*
  3  from t23
  4       , table (t23.emails) e
  5  where t23.id = 222
  6  /

NAME                           COLUMN_VALUE
------------------------------ ---------------------------------
Sam-I-Am                       sam_i_am@example.com
Sam-I-Am                       green_eggs_n_ham@yahoo.co.uk

SQL>

答案 1 :(得分:2)

执行此操作的标准方法是定义第二个表,您可以在其中存储每行一封电子邮件。

Oracle还支持nested tables,因此单个属性列可以包含多个值。