将分区 LIST 附加到 postgres 11 中的现有 table

Attach partition LIST to existing table in postgres 11

我正在尝试更改 table 以在 postgres 11 中使用分区列表。我已经尝试了几个小时,但我不断收到错误。

我有大量 table 客户,具有( client_id、customer_id、价值)。

我已经通过将旧的 table 重命名为 clients_old 创建了一个新的空 table 客户,然后创建了新的 table:CREATE TABLE clients( like clients_old including all).

从这里开始,我在尝试添加 LIST 分区时卡住了。

我尝试过:

ALTER TABLE Clients attach PARTITION BY LIST  (client_id) --> fail;
ALTER TABLE Clients attach PARTITION  LIST  (client_id) --> fail;
ALTER TABLE Clients ADD PARTITION  LIST  (client_id) --> fail;

我应该使用什么语法来改变 table 以使用分区?

Quote from the manual

It is not possible to turn a regular table into a partitioned table or vice versa

因此,您无法将现有的 non-partitioned table 更改为分区的 table。

您需要创建一个新的分区 table(使用不同的名称),创建所有必要的分区,然后将数据从旧 table 复制到新的分区 table.

类似于:

create table clients_partitioned
(
  .... all columns ...
)
PARTITION BY LIST  (client_id);

然后创建分区:

create table clients_1 
   partition of clients_partioned
   for values in (1,2,3);

create table clients_1 
   partition of clients_partioned
   for values in (4,5,6);

然后复制数据:

insert into clients_partitioned
select *
from clients;

完成后,您可以删除旧的 table 并重命名新的 table:

drop table clients;
alter table clients_partitioned rename to clients;

不要忘记 re-create 您的外键和索引。

我必须添加 for 标签才能添加分区:

create table clients_1 
partition of clients_partioned
for values in (4,5,6);

因为没有 for 是语法错误。