一般來說,我們二級分區表都會使用模版,如果沒有使用模版特性,那么就會報ERROR: no partitions specified at depth 2類似的錯誤。因為沒有模版,必須要顯式指定分區。
當然我們在建表的時候,如果沒有指定,那么后面也可以通過alter table 語句進行添加。下面我們通過一個例子看一下。
CREATE TABLE sales (trans_id integer,ctime timestamp without time zone,region text
)DISTRIBUTED BY (trans_id) PARTITION BY RANGE(ctime)SUBPARTITION BY LIST(region)(START ('2023-08-18 00:00:00'::timestamp without time zone) END ('2023-08-19 00:00:00'::timestamp without time zone) WITH (tablename='sales_1_prt_1', appendonly='false')(SUBPARTITION usa VALUES('usa') WITH (tablename='sales_1_prt_1_2_prt_usa', appendonly='false'),SUBPARTITION asia VALUES('asia') WITH (tablename='sales_1_prt_1_2_prt_asia', appendonly='false'),SUBPARTITION europe VALUES('europe') WITH (tablename='sales_1_prt_1_2_prt_europe', appendonly='false')));#如果只指定一級分區,添加分區會報錯
alter table sales add partition sale_3 start (date '2023-08-20') inclusive end (date '2023-08-21') exclusive ;
NOTICE: CREATE TABLE will create partition "sales_1_prt_sale_3" for table "sales"
ERROR: no partitions specified at depth 2
#必須顯式指定才可以添加成功
alter table sales add partition sale_2
START ('2023-08-19 00:00:00'::timestamp without time zone) END ('2023-08-20 00:00:00'::timestamp without time zone) (SUBPARTITION usa VALUES('usa'),SUBPARTITION asia VALUES('asia') ,SUBPARTITION europe VALUES('europe') );
#插入一些測試數據
insert into sales select generate_series(1,10000000) ,current_date ,'usa';
insert into sales select generate_series(1,10000000) ,current_date ,'asia';
insert into sales select generate_series(1,10000000) ,current_date ,'europe';#添加模版,就算之前有歷史數據,也是瞬間完成
ALTER TABLE sales
SET SUBPARTITION TEMPLATE(SUBPARTITION usa VALUES('usa') WITH (tablename='sales'),SUBPARTITION asia VALUES('asia') WITH (tablename='sales'),SUBPARTITION europe VALUES('europe') WITH (tablename='sales'))
;
NOTICE: adding level 1 subpartition template specification for relation "sales"
NOTICE: CREATE TABLE will create partition "sales_1_prt_subpartition_template" for table "sales"NOTICE: CREATE TABLE will create partition "sales" for table "sales_1_prt_subpartition_template"
NOTICE: CREATE TABLE will create partition "sales" for table "sales_1_prt_subpartition_template"
NOTICE: CREATE TABLE will create partition "sales" for table "sales_1_prt_subpartition_template"
ALTER TABLE#這次只指定一級分區就可以添加成功
alter table sales add partition sale_3 start (date '2023-08-20') inclusive end (date '2023-08-21') exclusive ;
NOTICE: CREATE TABLE will create partition "sales_1_prt_sale_2" for table "sales"
NOTICE: CREATE TABLE will create partition "sales_1_prt_sale_2_2_prt_usa" for table "sales_1_prt_sale_2"
NOTICE: CREATE TABLE will create partition "sales_1_prt_sale_2_2_prt_asia" for table "sales_1_prt_sale_2"
NOTICE: CREATE TABLE will create partition "sales_1_prt_sale_2_2_prt_europe" for table "sales_1_prt_sale_2"
ALTER TABLE
總結:
建表的時候,最好添加二級分區以后的模版,模版也可以后面變更,如果不加模版,添加分區的時候,必須指定子分區,所以分區級別越多,越復雜。