I'm using pgAdmin III for PostgreSQL but I have a problem with foreign keys between 3 tables. My tables are:

Locale with a primary key IDnegozio (integer type, no need to make it serial type) Orario with a primary key IDorario (integer type, no need to make it serial type) OrarioToLocale with two columns: IDlocaleT & IDorarioT (both integer).

I'm trying to make a foreign key between IDlocale -> IDlocaleT and IDorario -> IDorarioT so, I can have the relation that a Shop can have multiples time. The problem is that when I try to make these foreign keys, and an error occurs me: "no unique constraint matching is given keys for referenced table" and I don't understand why. I tried to google but I didn't find any answer! How can I do?

This is the code of the three tables:

CREATE TABLE public."Locale"
  "IDnegozio" integer NOT NULL DEFAULT nextval('"Locale_IDnegozio_seq"'::regclass),
  CONSTRAINT "Locale_pkey" PRIMARY KEY ("IDnegozio"),

CREATE TABLE public."Orario"
  "IDorario" integer NOT NULL DEFAULT nextval('"Orario_IDorario_seq"'::regclass),
  CONSTRAINT "Orario_pkey" PRIMARY KEY ("IDorario")

CREATE TABLE public."OrarioToLocale"
  "IDlocaleT" integer NOT NULL,
  "IDorarioT" integer NOT NULL

How can I do? Thank you advice!


You can put this right into the CREATE TABLE statements, and this can be a lot easier and shorter than what you have.

CREATE TABLE public.Locale ( IDnegozio serial PRIMARY KEY );
CREATE TABLE public.Orario ( IDorario serial PRIMARY KEY );
CREATE TABLE public.OrarioToLocale (
  IDlocaleT integer NOT NULL REFERENCES Locale,
  IDorarioT integer NOT NULL REFERENCES Orario,
  PRIMARY KEY ( IDlocaleT, IDorarioT )

I made OrarioToLocale with a composite primary but,

  1. You may decide you don't want that.
  2. If you do want that, than IDlocaleT, and IDorarioT are NOT NULL which means that even that doesn't need to be explicit.

It would have been good if you provided the foreign keys that failed. The following should work:

ALTER TABLE public."OrarioToLocale"
        REFERENCES public."Orario" ("IDorario");

and a similar constraint for Locale. Why do the attributes in OrarioToLocale end with a T?

  • "Why do the attributes in OrarioToLocale end with a T?"It's just for simplicity of reading, so I distinguish the fields.
    – JEricaM
    May 17 '17 at 9:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.