簡體   English   中英

如何提取一列數據並替換為外鍵?

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

如何將數據column (varchar, allows null)提取到新表中並用外鍵替換它?

我所知道的步驟:

  1. 創建一個具有遞增 PK 列和數據 varchar 列的新表。
  2. 使用insert-into-select將數據復制到新表中。
  3. 在原始表中更新/添加外鍵列???

我將如何制作外鍵,第 3 步?

已經存在的表t

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

被引用的表:

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

將不同且非空的值復制到引用的表中:

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

創建外鍵 ID 列:

alter table t
add column s_id int

使用外鍵 ID 填充新列:

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

創建約束:

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

刪除現在不需要的列:

alter table t
drop column s

最后結果:

\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)

測試約束:

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".

示例查詢:

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

在創建將數據插入新表時的第 2 步中,請確保您沒有添加重復項。 您也可以添加約束以不添加重復項。

同樣在你做3之前。

2a. 更改現有表添加一個新列,該列引用新外部表的 PK。

2b. 通過在varchar列上連接現有表和新表來填充新列,並使用 ForeignTable ID 進行更新。

2c。 刪除現有表中的 varchar 列。

現在您已准備好進行第 3 步添加外鍵。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM