天天看点

PG11创建分表

  • 实例
create table test
( 
  id bigserial ,
  create_time timestamp without time zone default now(),
  description varchar
) PARTITION BY RANGE(create_time);
alter table test add CONSTRAINT pk_test primary key(id,create_time);

create table test_default partition of test default;
create table test_2019_12_25 partition of test for values from ('2019-12-25') to ('2019-12-25 24:00:00');      
  • 实验
PG11创建分表
  • 添加数据
insert into TEST(DESCRIPTion) values('a'),('b');
insert into test (create_time, description) values('2019-12-25 12:12:00', 'c');
insert into test (create_time, description) values('2018-12-25 12:12:00', 'c');      
  • 查看数据
  • 新建一个分表, 如果default 分表中有数据落在该分区,则该分表会创建失败
imos=# create table test_2018_12_25 partition of test for values from ('2018-12-25') to ('2018-12-25 24:00:00');
ERROR:  updated partition constraint for default partition "test_default" would be violated by some row
imos=#       
  • 结论:
  • 可以看到分表与主表的结果一样,主表的id使用 bigserial的时候,分表也是的
  • 而且建立的分表其id的默认值与主表共用,所以我们建议在创建主表的时候,使用bigserial,以防止序列不够用的情况
  • 可以看到, 在查询的时候, 默认会先去非default 分表中查询数据,如果要查询的数据条数大于非default 分表中的数据,从会去default分表中查询数据