| From: | Sam Barnett-Cormack <s(dot)barnett-cormack(at)lancaster(dot)ac(dot)uk> | 
|---|---|
| To: | CHRIS HOOVER <CHRIS(dot)HOOVER(at)companiongroup(dot)com> | 
| Cc: | pgsql-admin(at)postgresql(dot)org | 
| Subject: | Re: Help with foreign key creation problem | 
| Date: | 2004-05-13 14:52:04 | 
| Message-ID: | Pine.LNX.4.58.0405131551230.2878@localhost.localdomain | 
| Views: | Whole Thread | Raw Message | Download mbox | Resend email | 
| Thread: | |
| Lists: | pgsql-admin | 
On Thu, 13 May 2004, CHRIS HOOVER wrote:
> I need some help understanding and creating foreign keys in postgresql.
>
> Here is an example of what I am trying to do:
>
> I have table 1 with:
> table1_id serial unique
> table1_col1 varchar
>
> I have table2 with:
> table2_id serial unique
> table1_id integer
> table2_col1 varchar
>
> When I try to create the foreign key with
> alter table "schema_name"."table1"
>   add foreign key ("table1_id")
>     references "schema_name"."table2"("table1_id")
>     on delete cascade
>     on update cascade
>     not deferrable;
>
> Postgres complains with:
> ERROR: UNIQUE constraint matching given keys for referenced table "table2" not
> found.
>
> Why is postgresql demanding a unique key on table2.table1_id?  It is a foreign
> key in a parent/child 1 to many relationship.
>
> Please help me understand what is going on, and what I am missunderstanding
> about foreign keys.
Only slightly, you're creating the wrong way around. You want to be
adding the foreign keep to table2.
--
Sam Barnett-Cormack
Software Developer                           |  Student of Physics & Maths
UK Mirror Service (http://www.mirror.ac.uk)  |  Lancaster University
| From | Date | Subject | |
|---|---|---|---|
| Next Message | CHRIS HOOVER | 2004-05-13 15:05:00 | Re: Help with foreign key creation problem | 
| Previous Message | Tom Lane | 2004-05-13 14:43:07 | Re: GNUmakefile size 0 |