简体   繁体   中英

Postgres - unique constraint

I'm facing the following error when I try to create that second table and I can't figure out why. For the table patente I want to be able to have (idfuncionario, titulo) as primary keys. I already tried to put the UNIQUE constraint as "UNIQUE (idfuncionario, titulo) as suggested in other topics.

CREATE TABLE publicacao
(
idfuncionario CHAR(5) NOT NULL,
titulo        VARCHAR(50) NOT NULL,
data          TIMESTAMP NOT NULL,
PRIMARY KEY (idfuncionario, titulo),
FOREIGN KEY(idfuncionario) REFERENCES trabalha(idfuncionario)
);

CREATE TABLE patente
(
idfuncionario CHAR(5) NOT NULL,
titulo        VARCHAR(50) NOT NULL,
datafim       TIMESTAMP NOT NULL,
descricao     VARCHAR(100) NOT NULL,
PRIMARY KEY (idfuncionario, titulo),
FOREIGN KEY(idfuncionario) REFERENCES trabalha(idfuncionario),
FOREIGN KEY(titulo) REFERENCES publicacao(titulo)
);

The message error:

ERROR: there is no unique constraint matching given keys for referenced table "publicacao" SQL state: 42830

I'm using Postgres 9.4 on a Windows 8.1 64bits

The foreign key referencing publicacao must refer to that table's primary key. So you want to do the following when creating patente :

CREATE TABLE patente
(
  idfuncionario CHAR(5) NOT NULL,
  titulo        VARCHAR(50) NOT NULL,
  datafim       TIMESTAMP NOT NULL,
  descricao     VARCHAR(100) NOT NULL,
  PRIMARY KEY (idfuncionario, titulo),
  FOREIGN KEY (idfuncionario) REFERENCES trabalha (idfuncionario),
  FOREIGN KEY (idfunctionario, titulo) REFERENCES publicacao (idfuncionario,titulo)
);

I think the foreign key on idfunctionario would be redundant in this case.

On the other hand, maybe when you created publicacao you intended for its primary key to include only the column titulo ?

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