Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Postgresql 如何将现有列转换为外键?_Postgresql_Foreign Keys - Fatal编程技术网

Postgresql 如何将现有列转换为外键?

Postgresql 如何将现有列转换为外键?,postgresql,foreign-keys,Postgresql,Foreign Keys,我有两张桌子 表a看起来像这样--第一行是列名,两者都包含字符: id | tractce | someString 1 | "0011900" | "Label here" 表b: id | tractFIPS 1 | "0011900" 如何将a.tractce转换为引用b.id的外键列 因此: id | tractce | someString 1 | 1 | "Label here" 只要表中没有任何恶意数据,这将添加约束: ALTER TABLE T

我有两张桌子

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

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

id | tractFIPS
1  | "0011900"
如何将
a.tractce
转换为引用
b.id
的外键列

因此:

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

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

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

你不能一步到位。您需要首先添加一个可以保存表
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;

在线示例:

对不起,我编辑了我的问题,以纠正一个拼写错误并澄清它。你的答案仍然适用吗?你不能在没有相同数据的列上使用外键(当然可以,但这绝不是一个好主意,而且毫无意义)。您必须将id与id或tractce与tractFIPS匹配。语法应该是相同的