postgres分区表修改分区规则

本文介绍了如何在PostgreSQL中动态调整分区表,将一个按列表分区的表从只接受'l_type'为'1'的分区,转变为同时接受'l_type'为'1'和'3'的分区。通过DETACH和ATTACH PARTITION操作,详细展示了数据迁移过程,并强调了在操作过程中需要注意的数据一致性问题。
摘要由CSDN通过智能技术生成

需求描述:如按列表分区,有一个分区表里存放的是 l_type in ('1'),现在想把这个分区改为t_type in ('1', '3')
postgres好像没有直接提供这样的方法,需要间接地进行一下修改,这里会用到 ATTACH PARTITIONDETACH PARTITION

为了演示,准备工作就是把数据建出来
创建父表

create table list_partition_test(id serial, l_type char(1)) partition by list( l_type );

创建子表

create table list_partition_test_1 partition of list_partition_test for values in ('1');
create table list_partition_test_2 partition of list_partition_test for values in ('2');

随意地添加数据,注意这里没有添加默认分区,也就是说不能太随意,如果添加l_type=3的记录是添加不进去的。

insert into list_partition_test (l_type) values ('1');
insert into list_partition_test (l_type) values ('2');
insert into list_partition_test (l_type) values ('2');
insert into list_partition_test (l_type) values ('2');
insert into list_partition_test (l_type) values ('1');

查一下数据吧

# 全表
select * from list_partition_test;
 id | l_type
----+--------
  1 | 1
  5 | 1
  2 | 2
  3 | 2
  4 | 2
(5 rows)
# 分区1
select * from list_partition_test_1;
 id | l_type
----+--------
  1 | 1
  5 | 1
(2 rows)
# 分区2
select * from list_partition_test_2;
 id | l_type
----+--------
  2 | 2
  3 | 2
  4 | 2
(3 rows)

现在想让分区1也能插入l_type=3的记录,需要这么做一下。
先看一下添加l_type=3会怎么样吧

insert into list_partition_test (l_type) values ('3');
ERROR:  no partition of relation "list_partition_test" found for row
DETAIL:  Partition key of the failing row contains (l_type) = (3).

人家没让添加成功
下面让它能添加成功
先将分区1从父表移除 – DETACH

ALTER TABLE list_partition_test DETACH PARTITION list_partition_test_1;

# 查一下数据
select * from list_partition_test;
 id | l_type
----+--------
  2 | 2
  3 | 2
  4 | 2
(3 rows)

再查数据时发现分区1的数据没了,当然会这样,因为数据就在人家分区1里,又不在list_partition_test里。不过不要慌,它又没丢。
这个时候把分区1再添加进来

ALTER TABLE list_partition_test ATTACH PARTITION list_partition_test_1  FOR VALUES IN ('1', '3');

# 再查一下数据
select * from list_partition_test;
 id | l_type
----+--------
  1 | 1
  5 | 1
  2 | 2
  3 | 2
  4 | 2
(5 rows)

再查数据时,发现数据已经回来了。就说不要慌的。
但是这里注意,添加分区1时,要保证list_partition_test_1表里的数据l_type都是1或3,要是再有个l_type=4,就ATTACH不成功了。
下面试一下效果,添加一条l_type=3的数据。

insert into list_partition_test (l_type) values ('3');

# 查一下数据再,可以发现l_type=3的数据已经插入成功了
select * from list_partition_test;
 id | l_type
----+--------
  1 | 1
  5 | 1
  7 | 3
  2 | 2
  3 | 2
  4 | 2
(6 rows)

# 而且l_type=3的数据在分区1里
select * from list_partition_test_1;
 id | l_type
----+--------
  1 | 1
  5 | 1
  7 | 3

OKAY,搞完了。

生产环境数据量通常会很大,也可以采用这样的方法,但要小心慢来。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值