Domanda

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!

È stato utile?

Soluzione

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.

Altri suggerimenti

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

ALTER TABLE public."OrarioToLocale"
    ADD CONSTRAINT FK_... FOREIGN KEY ("IDorarioT")
        REFERENCES public."Orario" ("IDorario");

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a dba.stackexchange
scroll top