Friday, 15 January 2010

postgresql - Postgres: create foreign key relationship, getting 'Key is not present in table'? -


I am working in postgrass 9 and I want to create a foreign key relationship for two tables which are not currently is.

These are my tables:

  # \ d frontend_item; Table "public.frontend_item" column | | Type | Modifier ------------------- + ------------------------- + --- -------------------------------------------------- --------------- ID | Integer | Null default is not the next line ('frontend_prescription_id_seq' :: regclass) presentation_code | Character is changing (15) | Faucet pct_code no | Different character (3) | Null not indexed: "frontend_item_pkey" primary key, btree (id) # \ d frontend_pct; Column | Type | Modifier ------------ + -------------------------- + --------- - Code | Different character (3) | Null not indexed: "frontend_pct_pkey" primary key, btree (code) "frontend_pct_code_1df55e2c36c298b2_like" btree (code varchar_pattern_ops)  

I'm trying this:

  # Add optional table frontend_item contract pct_fk foreign key (pct_code) reference frontend_pct (code) at DELETE CASCADE;  

But I get this error:

  Error: Enter on the table "frontend_item" or the update violates the foreign key barrier "pct_fk" extension: Key (pct_code) = (5 HQ) is not present in the table "frontend_pct"  

I think this makes sense because currently the frontend_pct table Is empty, while frontend_item contains values ​​

First of all, the syntax for my optional table is correct?

Second, there frontend_pct ? It would be great if postgres had a way of saying "to make foreign keys, and if they are not present then enter the value in the foreign key table".

Your syntax looks correct.

No, there is no automated way to include the required values.
You can manually do it yourself before adding constraints. In your case there should be something

  select INSERT in frontend_pct (code) from code (select pct_code as frontend_item Is not in pct_code (select code from frontend_pct));  

If you have too many data then the query may be every ..


No comments:

Post a Comment