引用分区允许表基于其参照约束进行分区,分区键值通过现有的父子关系进行解析。这意味着,有引用关系的表能够继承父表的分区键值,而不需要重复的键。这种逻辑依存也能够自动进行分区维护,使得应用开发更加容易,且不易出错。
SQL> CREATE TABLE orders
( order_id NUMBER(12),
order_date DATE,
order_mode VARCHAR2(8),
customer_id NUMBER(6),
CONSTRAINT orders_pk PRIMARY KEY(order_id)
)
PARTITION BY RANGE(order_date)
(PARTITION Q1_2005 VALUES LESS THAN
(TO_DATE(’2005-4-1′,’yyyy-mm-dd’)),
PARTITION Q2_2005 VALUES LESS THAN
(TO_DATE(’2005-7-1′,’yyyy-mm-dd’)),
PARTITION Q3_2005 VALUES LESS THAN
(TO_DATE(’2005-10-1′,’yyyy-mm-dd’)),
PARTITION Q4_2005 VALUES LESS THAN
(TO_DATE(’2006-1-1′,’yyyy-mm-dd’)))
;
Table created.
SQL> CREATE TABLE order_items
( order_id NUMBER(12) NOT NULL,
line_item_id NUMBER(3) NOT NULL,
product_id NUMBER(6) NOT NULL,
unit_price NUMBER(8,2),
quantity NUMBER(8),
CONSTRAINT order_items_fk
FOREIGN KEY(order_id) REFERENCES orders(order_id)
)
PARTITION BY REFERENCE(order_items_fk);
Table created.
上面的例子创建了一张orders表,在order_date列上进行范围分区,分别命名为Q1_2005、Q2_2005、Q3_2005、Q4_2005。接下来再创建一张引用分区表,以orders的主键order_id为外键。
SQL> select PARTITION_NAME from dba_tab_partitions
2 where table_name=’ORDERS’;
PARTITION_NAME
——————————
Q1_2005
Q2_2005
Q3_2005
Q4_2005
SQL> select PARTITION_NAME from dba_tab_partitions
2 where table_name=’ORDER_ITEMS’;
PARTITION_NAME
——————————
Q1_2005
Q2_2005
Q3_2005
Q4_2005
从上面的查询可以看出,order_itmes表自动创建了和父表相对应的分区。不能指定引用分区的上下限,但可以给分区命名,如果没有显示的给各个分区命名,将自动继承父表的分区名称。一旦父表的分区发生变化,子表分区也会自动适应,而单独修改子表分区则不被允许。
SQL> alter table orders drop partition q1_2005;
Table altered.
SQL> select PARTITION_NAME from dba_tab_partitions where table_name=’ORDERS’;
PARTITION_NAME
——————————
Q2_2005
Q3_2005
Q4_2005
SQL> select PARTITION_NAME from dba_tab_partitions where table_name=’ORDER_ITEMS’;
PARTITION_NAME
——————————
Q2_2005
Q3_2005
Q4_2005
SQL> alter table order_items drop partition q2_2005;
alter table order_items drop partition q2_2005
*
ERROR at line 1:
ORA-14255: table is not partitioned by Range, List, Composite Range or
Composite List method