加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

PostgreSQL中的派生类型

发布时间:2020-12-13 16:09:48 所属栏目:百科 来源:网络整理
导读:是否可以从类型中创建“派生类型”?就像在 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
是否可以从类型中创建“派生类型”?就像在 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 manually
select 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读