【问题标题】:How to add a column to typed table without altering type in PostgreSQL?如何在不改变 PostgreSQL 类型的情况下向类型化表添加列?
【发布时间】:2017-05-11 13:25:13
【问题描述】:

我使用的是 PostgreSQL 9.5,我有一个描述列集合的 TYPE:

CREATE TYPE datastore.record AS
   (recordid bigint,
    ...
    tags text[]);

我已经创建了许多依赖于这个 TYPE 的表:

CREATE TABLE datastore.events
OF datastore.record;

现在我想在不更新 TYPE 的情况下向依赖此 TYPE 的表添加一列。我认为这是不可能的,因此我想知道是否有办法在不丢失任何数据或将表复制到临时表中的情况下解除我的表与该 TYPE 的绑定?

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    为此目的有一个特殊选项not of。每the documentation

    NOT OF - 此表单将类型化表与其类型分离。

    所以:

    alter table my_table not of;
    alter table my_table add new_column integer;
    

    【讨论】:

    • 谢谢,它成功了。我不知道 NOT OF 关键字。我所有的关系都被保留了,
    • 太棒了。我不知道not of
    【解决方案2】:

    如果你不想破坏关系:

    --drop table if exists t2;
    --drop table if exists t1;
    --drop type if exists tp_foo;
    
    create type tp_foo as (i int, x int);
    
    create table t1 of tp_foo;
    create table t2 (y text) inherits(t1);
    
    alter type tp_foo add attribute z date cascade;
    
    select * from t2;
    

    【讨论】:

    • 感谢您分享此方法。刚刚测试过,它会减轻我的维护。
    猜你喜欢
    • 1970-01-01
    • 2018-01-16
    • 2022-01-16
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多