简体   繁体   中英

How to extract a column of data and replace with foreign key?

How do you extract a column (varchar, allows null) of data into a new table and replace it with a foreign key?

Steps as I know them:

  1. Create a new table with an incrementing PK column and data varchar column.
  2. Use insert-into-select to copy the data into the new table.
  3. Update/add a foreign key column in the original table???

How would I make the foreign key, step 3?

The already existent table t :

create table t (s text);
insert into t (s) values ('a'), ('a'), ('b'), (null)

The to be referenced table:

create table s (
    s_id serial primary key,
    s text
)

Copy the distinct and not null values to the referenced table:

insert into s (s)
select distinct s
from t
where s is not null

Create the foregin key id column:

alter table t
add column s_id int

Populate the new column with the foreign key ids:

update t
set s_id = s.s_id
from s
where t.s = s.s

Create the constraint:

alter table t
add foreign key (s_id) references s (s_id)

Drop the now unnecessary column:

alter table t
drop column s

Final result:

\d t
    Table "public.t"
 Column |  Type   | Modifiers 
--------+---------+-----------
 s_id   | integer | 
Foreign-key constraints:
    "t_s_id_fkey" FOREIGN KEY (s_id) REFERENCES s(s_id)

\d s
                        Table "public.s"
 Column |  Type   |                    Modifiers                     
--------+---------+--------------------------------------------------
 s_id   | integer | not null default nextval('s_s_id_seq'::regclass)
 s      | text    | 
Indexes:
    "s_pkey" PRIMARY KEY, btree (s_id)
Referenced by:
    TABLE "t" CONSTRAINT "t_s_id_fkey" FOREIGN KEY (s_id) REFERENCES s(s_id)

Test the constraint:

insert into t (s_id) values (3);
ERROR:  insert or update on table "t" violates foreign key constraint "t_s_id_fkey"
DETAIL:  Key (s_id)=(3) is not present in table "s".

A sample query:

select s_id, coalesce(s, 'null') as s
from t left join s using(s_id);
 s_id |  s   
------+------
      | null
    2 | a
    2 | a
    1 | b

In step 2 when creating inserting the data into new table make sure you are not adding duplicates. Also you can add constraints to not add duplicates.

Also before you do 3.

2a. Alter existing Table add a new column which will be refrencing the PK of your new foreign table.

2b. Populate the new column by joining your existing table and your new table on the varchar column and update with ForeignTable ID.

2c. Drop the varchar column in your existing table.

Now you are ready for step 3 to add foreign key.

ALTER TABLE ExistingTable
ADD CONSTRAINT yourFK
FOREIGN KEY (yourColumnNameID)
REFRENCES yourNewForeginTable(ColumnNameID)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM