PostgreSQL中的派生类型

PostgreSQL中的派生类型,第1张

概述是否可以从类型中创建“派生类型”?就像在 Java中扩展一样. 例如,我需要这些类型: create type mytype as ( f1 int, --many other fields... fn varchar(10));create type mytype_extended as ( f1 int, --many other fields.. 是否可以从类型中创建“派生类型”?就像在 Java中扩展一样.

例如,我需要这些类型:

create type mytype as (    f1 int,--many other fIElds...    fn varchar(10));create type mytype_extended as (    f1 int,--many other fIElds...    fn varchar(10),fx int --one fIEld more);

你可以看到这是多余的.如果将来我改变了mytype,我也需要更改mytype_extended.

我试过这个:

create type mytype as (    f1 int,--many other fIElds...    fn varchar(10));create type mytype_extended as (    mt mytype,fx int --one fIEld more);

但这导致mytype_extended只有2个字段,mt(我认为是复杂类型)和fx,而不是f1,f2 … fn,fx.

有没有办法实现这个目标?

解决方法 在Postgresql中,没有直接的类型继承,但是你有几个选择:

1. Table inheritance

您可以创建继承表来创建继承类型(Postgresql将始终为每个表创建一个具有相同名称的复合类型):

create table supertable (  foo   int,bar   text);create table subtable (  baz   int) inherits (supertable);

2. Construct views using each other

因为视图(实际上)是表(使用rules),所以也为每个表创建一个类型:

create vIEw supervIEw  as select null::int  foo,null::text bar;create vIEw subvIEw  as select supervIEw.*,null::int  baz     from   supervIEw;

3. Type composition

这就是你尝试过的.一般来说,你对这个有更多的控制权:

create type supertype as (  foo   int,bar   text);create type subtype as (  super supertype,baz   int);-- resolve composition manuallyselect get_foo(v),-- this will call get_foo(subtype)       get_foo((v).super) -- this will call get_foo(supertype)from   (values (((1,'2'),3)::subtype)) v(v);

 1真正的类型继承?

PostgreSQL’s documentation explicitly says,表继承不是标准的类型继承:

sql:1999 and later define a type inheritance feature,which differs in many respects from the features described here.

尽管如此,继承表的自动创建类型确实像真正的继承类型一样工作(可以使用它们,可以使用超类型):

-- if there is a get_foo(supertable) function,-- but there is no get_foo(subtable) function:select get_foo((1,'2')::supertable);  -- will call get_foo(supertable)select get_foo((1,'2',3)::subtable); -- will also call get_foo(supertable)

SQLFiddle

总结

以上是内存溢出为你收集整理的PostgreSQL中的派生类型全部内容,希望文章能够帮你解决PostgreSQL中的派生类型所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/1163067.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-01
下一篇 2022-06-01

发表评论

登录后才能评论

评论列表(0条)

保存