在PostgreSQL中创建两种类型的表

时间:2014-02-04 22:48:09

标签: sql postgresql sql-types

我创建了两种类型:

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

1 个答案:

答案 0 :(得分:3)

您无法将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