简体   繁体   中英

Creating a Primary Key with multiple value (including Foreign Keys)

I'am trying to create those tables using PostgreSQL:

create table OrgaoSuperior(
cod_superior int unique,
primary key(cod_superior),
nome_superior varchar(2000)
);

create table OrgaoSubordinado(
cod_superior int,
cod_subordinado int unique,
primary key(cod_superior,cod_subordinado),
foreign key(cod_superior) references OrgaoSuperior(cod_superior),
nome_subordinado varchar(2000)
);

create table Subfuncao(
cod_subfuncao int not null unique,
primary key(cod_subfuncao),
nome_subfuncao varchar(2000)
);

create table Acao(
cod_subordinado int not null,
cod_subfuncao int not null,
cod_acao int not null,
primary key(cod_subordinado,cod_subfuncao,cod_acao),
foreign key(cod_subordinado) references OrgaoSubordinado(cod_subordinado),
foreign key(cod_subfuncao) references Subfuncao(cod_subfuncao),
nome_acao varchar(2000)
);

But I'm getting SQL state 42830. I already tried using a UNIQUE constraint on cod_acao, but I don't want only cod_acao to be unique (it may repeat its values), I want the combination of cod_subordinado,cod_subfuncao and cod_acao to be unique (and to be the PRIMARY KEY of this table). Is there any workaround for this problem?

您只能在表的一列上使用主键,并且主键也不为null和唯一。

SQL state 42830 has an alias of invalid_foreign_key .

A foreign key must reference columns that either are a primary key or form a unique constraint.

But that seems to be the case in your tables.

Your code works with even PostgreSQL 8.3.20 - 9.3.1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM