Pg库建分区表(pg9.6之后的插件pg_pathman可以建分区,比下面两种方法方便很多)
下面是分别介绍使用触发器和Ruler建分区表的步骤:
一、使用触发器
1、建分区表(默认父表已经建了):
假设按月分区,按the_date字段分区
CREATE TABLE table_y2013m01
(
CONSTRAINT table_y2013m01 the_date_checkCHECK(the_date >= '2013-01-01' AND the_date < '2013-02-01')(类型需要转的时候用cast)
)
INHERITS (父表)(INHERITS相当于继承)
WITH (
OIDS=FALSE
);
需要多个分区表,就写多个create语句。
2、写函数:
-- Function:func_funcname()
-- DROP FUNCTION func_funcname();
CREATE OR REPLACE FUNCTION func_funcname()
RETURNS trigger AS
$BODY$
BEGIN
IF ( NEW.the_date < DATE '20130201')THEN
INSERT INTO table_2013m01 VALUES(NEW.*);
…………………………(这里如果建多个分区表,就多个elsif)
ELSIF ( NEW.the_date >= DATE '20161201' AND
NEW.the_date < DATE '20170101') THEN
INSERT INTO table_y2016m12 VALUES(NEW.*);
ELSE
RAISE EXCEPTION 'Date out of range. Fix the function!' ;
END IF;
RETURN NULL;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION func_funcname()
OWNER TO pierdata;
3、需要触发器
CREATE TRIGGER 自己取名
BEFORE INSERT
ON 父表
FOR EACH ROW
EXECUTE PROCEDURE func_funcname();
新插入数据时触发,即inset才会触发。
二、使用Ruler
1、建父表:
CREATE TABLE ckf_test (
student_id integer,
name varchar(32),
score integer
);
2、建分区表
CREATE TABLE ckf_test_p1
(CHECK(score >= 60 )) INHERITS (ckf_test) ;
CREATE TABLE ckf_test_p2
(CHECK(score < 60)) INHERITS(ckf_test) ;
3、建Ruler
CREATE OR REPLACE RULE insert_ckf_test_p1
AS ON INSERT TO ckf_test
WHERE score >= 60
DO INSTEAD
INSERT INTO ckf_test_p1VALUES(NEW.*);
CREATE OR REPLACE RULE insert_ckf_test_p2
AS ON INSERT TO ckf_test
WHERE score < 60
DO INSTEAD
INSERT INTO ckf_test_p2VALUES(NEW.*);
不需要函数了~~~~
测试一下:
INSERT INTO ckf_test (name,score) VALUES('Jim',77);
INSERT INTO ckf_test (name,score) VALUES('Frank',56);
INSERT INTO ckf_test (name,score) VALUES('Bean',88);
INSERT INTO ckf_test (name,score) VALUES('John',47);
INSERT INTO ckf_test (name,score) VALUES('Albert','87');
INSERT INTO ckf_test (name,score) VALUES('Joey','60');