【问题标题】:How to extract a column of data and replace with foreign key?如何提取一列数据并用外键替换?
【发布时间】:2015-10-01 03:35:18
【问题描述】:

如何将column (varchar, allows null) 的数据提取到新表中并用外键替换?

据我所知的步骤:

  1. 使用递增的 PK 列和数据 varchar 创建一个新表 柱子。
  2. 使用insert-into-select将数据复制到新的 桌子。
  3. 在原表中更新/添加外键列???

如何制作外键,第 3 步?

【问题讨论】:

  • “用外键替换”是什么意思?..
  • 我认为 Adam 的意思是“通过将列的条目转换为对通过从列中获取不同值并将它们存储在新的单独表中而创建的查找表的引用来进行标准化”
  • @CraigRinger 正确,这正是我想要做的。

标签: sql postgresql foreign-keys constraints database-normalization


【解决方案1】:

已经存在的表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】:

    在创建将数据插入新表的第 2 步中,请确保 您没有添加重复项。您也可以添加约束以不添加 重复。

    在你做 3 之前。

    2a。更改现有表添加一个 引用的新列 您的新外表的 PK。

    2b。通过加入您现有的表格和您的表格来填充新列 varchar 列上的新表并使用 ForeignTable ID 更新。

    2c。删除现有表中的 varchar 列。

    现在您已准备好进行第 3 步添加外键。

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

    【讨论】:

      猜你喜欢
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 2011-09-06
      • 2018-01-28
      • 1970-01-01
      • 2017-11-29
      • 2021-11-12
      相关资源
      最近更新 更多