POSTGRE 分表策略

1、通过 CHECK
1.1)创建子表

create table "test_2016" (CHECK (year='2016')) inherits (test);
CREATE INDEX index_test_2016  ON "test_2016" (name);

create table "test_2017" (CHECK (year='2017')) inherits (test);
CREATE INDEX index_test_2017  ON "test_2017" (name);

1.2)创建函数

CREATE OR REPLACE FUNCTION "public"."function_insert_test"()
  RETURNS "pg_catalog"."trigger" AS $BODY$
      BEGIN
       IF   
         NEW.year ='2016'
        THEN
        INSERT INTO "test_2016" VALUES (NEW.*);
		ELSIF  
         NEW.year ='2017'
        THEN
        INSERT INTO "test_2017" VALUES (NEW.*);
        END IF; 
      RETURN NULL;
      END;
      $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100

1.3)创建触发器

create trigger trigger_insert_test before insert on test for each row execute procedure function_insert_test();

2、通过 partition
2.1)创建主表

CREATE TABLE "public"."test" (
  "name" varchar(50),
  "address" varchar(150),
  "year" varchar(10)
)partition by LIST (year)

2.2)创建分区表

create table test_2016 partition of test for values in ('2016');
CREATE INDEX index_test_2016  ON test_2016 (name);

create table test_2017 partition of test for values in ('2017');
CREATE INDEX index_test_2017  ON test_2017 (name);

粗浅结论:使用 partition时,分区表不是物理表,在设计表中有个分区选项中,表数据不直观,并且在数据量达到1亿多以后,效率降低。在数据量少时,比 CHECK 的方式效率要高。

你可能感兴趣的:(java)