【问题标题】:How do I convert an existing column to Foreign Key?如何将现有列转换为外键?
【发布时间】:2018-07-08 16:28:00
【问题描述】:

我有两张桌子。

a 看起来像这样——第一行是列名,都包含字符:

id |  tractce   | someString
1  |  "0011900" | "Label here"

b

id | tractFIPS
1  | "0011900"

如何将a.tractce 转换为引用b.id 的外键列?

所以它是:

id |  tractce | someString
1  |  1       | "Label here"

【问题讨论】:

    标签: postgresql foreign-keys


    【解决方案1】:

    只要表中没有任何流氓数据,这将添加约束:

    ALTER TABLE TableName
    ADD CONSTRAINT fk_Name
    FOREIGN KEY (ColumnName) 
    REFERENCES TableName(ColumnName);
    

    【讨论】:

    • 抱歉,我编辑了我的问题以修正一个错字并澄清它。你的答案仍然适用吗?
    • 你不能在没有相同数据的列上使用外键(当然你可以,但这绝不是一个好主意,而且毫无意义)。您必须将 id 与 id 或 tractce 与 tractFIPS 匹配。语法是一样的
    【解决方案2】:

    您不能一步完成。您需要先添加一个可以保存表b 主键的新列,然后更新表a,然后添加外键并删除旧列:

    alter table a add b_id int;
    
    update a
       set b_id = b.id
    from b 
    where a.tractce = b.tractfips;
    
    
    alter table a drop column tractce;
    alter table a add constraint fk_a_b foreign key (b_id) references b;
    

    在线示例:http://rextester.com/LPWNHK59722

    【讨论】:

      猜你喜欢
      • 2018-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      • 2019-10-12
      • 1970-01-01
      • 2021-05-16
      相关资源
      最近更新 更多