1.创建主表
CREATE TABLE main_table (id bigserial NOT NULL,content text,create_date date NOT NULL
) PARTITION BY RANGE (create_date);
2.创建分区
按年进行分区
CREATE TABLE partition_2024 PARTITION OF main_table
FOR VALUES FROM ('2024-01-01') TO ('2025-01-01');CREATE TABLE partition_2025 PARTITION OF main_table
FOR VALUES FROM ('2025-01-01') TO ('2026-01-01');
3.插入数据
insert into main_table values('test1', '2024-01-04');insert into main_table values('test2', '2024-06-12');insert into main_table values('test3', '2025-01-27');insert into main_table values('test4', '2025-09-01');
4.查询数据
select * from main_table where create_date > '2024-10-20'
5.报错问题
insert into main_table values('test1', '2023-01-04');
报错信息:
“main_table” found for row 详细:Partition key of the failing row contains (create_date) = (2023-01-04).
说明:
因为按照日期(2023-01-04),没有创建2023年的分区导致报错,如果在实际项目中,需要创建job对分区进行新增和删除。