修改 table 的模式以使其从另一个模式继承而不重新创建 table 或重新插入数据
Modifying the schema of a table to make it inherit from another one without recreating the table or reinserting the data
我的 PostgreSQL 数据库中有几个 table,它们有几个公共列。我认为如果我将这些公共列移动到一个新的 table 中并使 table 继承自这个新的 table 是个好主意。例如:
create table foo_bar (
code varchar(9) primary key,
name varchar,
bar integer
);
重构后:
create table foo (
code varchar(9) primary key,
name varchar
);
create table foo_bar (
bar integer
) inherits (foo);
问题是,我在 foo_bar
中有很多数据,还有很多引用此 table 的视图。
是否可以更改 foo_bar
的定义以实现上述更改而不删除 table 中的数据?
CREATE TABLE foo (
code varchar(9),
name varchar
);
ALTER TABLE foo_bar INHERIT foo;
这可能是个好主意,也可能不是。数据库设计不完全是面向对象的编程。还有一些caveats.
A serious limitation of the inheritance feature is that indexes
(including unique constraints) and foreign key constraints only apply
to single tables, not to their inheritance children. This is true on
both the referencing and referenced sides of a foreign key constraint.
link 中还描述了一些您需要注意的问题。
如果您真的想继续这样做,Laurenz Albe 的回答中给出了如何更改 table。
我的 PostgreSQL 数据库中有几个 table,它们有几个公共列。我认为如果我将这些公共列移动到一个新的 table 中并使 table 继承自这个新的 table 是个好主意。例如:
create table foo_bar (
code varchar(9) primary key,
name varchar,
bar integer
);
重构后:
create table foo (
code varchar(9) primary key,
name varchar
);
create table foo_bar (
bar integer
) inherits (foo);
问题是,我在 foo_bar
中有很多数据,还有很多引用此 table 的视图。
是否可以更改 foo_bar
的定义以实现上述更改而不删除 table 中的数据?
CREATE TABLE foo (
code varchar(9),
name varchar
);
ALTER TABLE foo_bar INHERIT foo;
这可能是个好主意,也可能不是。数据库设计不完全是面向对象的编程。还有一些caveats.
A serious limitation of the inheritance feature is that indexes (including unique constraints) and foreign key constraints only apply to single tables, not to their inheritance children. This is true on both the referencing and referenced sides of a foreign key constraint.
link 中还描述了一些您需要注意的问题。
如果您真的想继续这样做,Laurenz Albe 的回答中给出了如何更改 table。