Create a table of two types in PostgreSQL

我怕爱的太早我们不能终老 提交于 2019-11-27 07:29:05

问题


I have created two 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);

And I want to create a table that consists of these two types. I know that for a table that consists of one type, it's:

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

Is there any way to do that for the two types I created above?

What I tried doing(which is wrong), is creating a third type that contains the first two:

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

and then creating the table:

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

But it doesn't work. I get this error:

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:


You cannot make prod_id the primary key of table1 because the only columns are the two composite types info and movie. You cannot access the base types of these composite types in a PRIMARY KEY clause.

What you were trying to do works with a pk constraint on info or movie.
Except, it's probably not what you were looking for, which is not possible this way.

You could implement something like this with ...

Inheritance

Here you can inherit from multiple parent tables (substitute for your types). Example:

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.

Be sure to read about limitations of inheritance in the manual.



来源:https://stackoverflow.com/questions/21565183/create-a-table-of-two-types-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!