0

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

1 Answer 1

2

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?

Sign up to request clarification or add additional context in comments.

2 Comments

I couldn't solve using your hint. The title for PK change would work for now, but probably i would have some functionalities issues later on. I did some changes at design level so is working smoothly now. But I really appreciated your help. Thank you and have a nice day.
Alessandro, I'm sorry if my answer wasn't helpful. The basic issue is that a foreign key must refer to a unique index (preferably the primary key) of the parent table - that is how referential integrity is preserved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.