简体   繁体   English

创建具有多个值的主键(包括外键)

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

I'am trying to create those tables using PostgreSQL: 我正在尝试使用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). 但是我正在获取SQL状态42830。我已经尝试过对cod_acao使用UNIQUE约束,但是我不希望仅cod_acao是唯一的(它可以重复其值),我希望cod_subordinado,cod_subfuncao和cod_acao的组合是唯一的唯一(并成为此表的PRIMARY KEY)。 Is there any workaround for this problem? 有没有解决此问题的方法?

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

SQL state 42830 has an alias of invalid_foreign_key . SQL状态 42830具有别名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 您的代码工作甚至PostgreSQL的8.3.20 - 9.3.1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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