【问题标题】:Create a table of two types in PostgreSQL在 PostgreSQL 中创建两种类型的表
【发布时间】:2014-03-01 04:07:21
【问题描述】:

我创建了两种类型:

Create  Type info_typ_1 AS (
Prod_id integer, 
category integer);

Create Type movie_typ AS(
title varchar(50),
actor varchar(50),
price float);

我想创建一个包含这两种类型的表。我知道对于包含一种类型的表,它是:

CREATE TABLE Table1 of type1
(
  primary key(prod_id)
);

对于我上面创建的两种类型有什么办法吗?

我尝试做的(这是错误的)是创建包含前两个的第三种类型:

Create Type info_ AS (
info info_typ_1,
movie movie_typ);

然后创建表:

CREATE TABLE table1 of info_
(
  primary key(Prod_id)
);

但它不起作用。我收到此错误:

ERROR:  column "prod_id" named in key does not exist
LINE 3:   primary key(Prod_id)
          ^
********** Error **********

ERROR: column "prod_id" named in key does not exist
SQL state: 42703
Character: 43

【问题讨论】:

    标签: sql postgresql sql-types


    【解决方案1】:

    您不能将prod_id 设为table1 的主键,因为唯一的列是infomovie 这两个复合类型。您不能在 PRIMARY KEY 子句中访问这些复合类型的基类型。

    您尝试执行的操作适用于 infomovie 上的 pk 约束。
    除了,它可能不是你要找的东西,这是不可能的。

    您可以使用 ...

    来实现 之类的

    Inheritance

    在这里您可以从多个父表继承(替代您的类型)。示例:

    CREATE TABLE info (
      prod_id integer
     ,category integer
    );
    
    CREATE TABLE movie (
       title text
      ,actor text
      ,price float
    );
    
    CREATE  TABLE movie_info (
       PRIMARY KEY(prod_id)             -- now we can use the base column!
    )
    INHERITS (info, movie);
    
    INSERT INTO movie_info (prod_id, category, title, actor, price)
    VALUES (1, 2, 'who donnit?', 'James Dean', '15.90');
    
    SELECT * FROM movie_info;
    

    -> SQLfiddle demonstrating both.

    请务必阅读limitations of inheritance in the manual

    【讨论】:

    • 有没有办法用type 做到这一点?而不是创建三个表
    • @Shevliaskovic:继承需要表。不过,我认为创建表没有任何害处。您甚至可以将它们存储在一些专用模式中。 Like demonstrated in this related answer.
    猜你喜欢
    • 2014-10-26
    • 2021-12-02
    • 2017-04-07
    • 2023-01-21
    • 2020-03-22
    • 2015-10-03
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多