创建一个新的子表:
zx@ORCL>create table order_line_items
2 (
3 order# number NOT NULL,
4 line# number NOT NULL,
5 data varchar2(30),
6 constraint c1_pk primary key(order#,line#),
7 constraint c1_fk_p foreign key(order#) references orders
8 )
9 enable row movement
10 partition by reference(c1_fk_p)
11 /
Table created.
zx@ORCL>insert into order_line_items values
2 ( 1, 1, 'yyy' );
1 row created.
zx@ORCL>insert into order_line_items values
2 ( 2, 1, 'yyy' );
1 row created.
zx@ORCL>commit;
Commit complete.
神奇之处就在CREATE TABLE语句的第10行。在这里,我们将区间分区语句替换为PARTITION BY REFERENCE。
这允许我们指定要使用的外键约束,从而发现分区机制。在这里可以看到外键指向ORDERS表——数据库读取ORDERS表的结构,并发现它有两个分区。因此,子表会有两个分区。实际上,如果现在查询数据字典可以得到:
zx@ORCL>set linesize 200
zx@ORCL>col table for a20
zx@ORCL>col partition_name for a20
zx@ORCL>select table_name, partition_name
2 from user_tab_partitions
3 where table_name in ( 'ORDERS', 'ORDER_LINE_ITEMS' )
4 order by table_name, partition_name
5 /
TABLE_NAME PARTITION_NAME
------------------------------------------------------------------------------------------ --------------------
ORDERS PART_2016
ORDERS PART_2017
ORDER_LINE_ITEMS PART_2016
ORDER_LINE_ITEMS PART_2017
可以看到两个表的结构完全相同。另外,由于数据库知道这两个表是相关联的,可以删除父表分区,并让它自动清除相关的子表分区(因为子表从父表继承而来,所以父表分区结构的任何调整都会向下级联传递到子表分区):
zx@ORCL>alter table orders drop partition part_2016 update global indexes;
Table altered.
zx@ORCL>select table_name, partition_name
2 from user_tab_partitions
3 where table_name in ( 'ORDERS', 'ORDER_LINE_ITEMS' )
4 order by table_name, partition_name
5 /
TABLE_NAME PARTITION_NAME
------------------------------------------------------------------------------------------ --------------------
ORDERS PART_2017
ORDER_LINE_ITEMS PART_2017