使用外键约束将行从 master table 移动到 child table

Move rows from master table to child table with foreign key constraints

我有一个名为 posts 的 table,行数约为 1000 万,它降低了我的查询性能,所以我正在考虑使用分区优化它 child tables,其中每个 child table 将包含一年的记录。

我目前有以下策略:

  1. 通过

    创建没有INHERIT约束的childtable
    CREATE TABLE posts_2017 AS
    (SELECT * from posts where inserted_at < '2018-01-01 00:00:00');
    
  2. 之后创建继承关系

    ALTER TABLE posts_2017 inherit posts;
    
  3. 之后将CHECK约束添加到childtable

现在它运行良好,但现在如果我查询 SELECT * from posts,我会得到 2017 年 post 的重复结果。我的下一步是使用另一个查询

从 master table 中删除它们
DELETE FROM ONLY posts where inserted_at < '2018-01-01 00:00:00'

但我遇到了另一个障碍,其中另一个 table 实际上有一个引用那些 2017 年记录的外键。

例如,假设我有一个 table users_posts 只有 user_idpost_id 列,如果此 [=54] 中的一行,我的删除查询将失败=] 引用 2017 post。

在这种情况下我有哪些选择?

您目前不能有指向分区表的外键。

此功能有 a “work in progress” patch,因此它可能会出现在 PostgreSQL v12 中。

目前,如果要分区,则必须在没有外键约束的情况下进行。