Create a table of two types in PostgreSQL

荒凉一梦 提交于 2019-11-28 13:05:10

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.

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