我有两个表表1:
cs111=# \d structure;
Table "public.structure"
Column | Type | Collation | Nullable | Default
----------+---------+-----------+----------+---------
page_url | text | | |
arm_id | integer | | |
Indexes:
"structure_arm_id_key" UNIQUE CONSTRAINT, btree (arm_id)
和表2:
cs111=# \d bandit_pages;
Table "public.bandit_pages"
Column | Type | Collation | Nullable | Default
-------------+---------+-----------+----------+---------
campaign_id | text | | |
arm_id | integer | | |
status | boolean | | |
我想使arm_id
表中的structure
成为bandit_pages
表的外键,但要位于campaign_id
的列上。这些表已经制作好了,所以我不确定如何更改这些表。请帮忙。
答案 0 :(得分:1)
整个问题似乎都朝着错误的方向发展,但是无论如何。
根据以下假设:
campaign_id
实际上是一个错误地存储为字符串的数字campaign_id
确实存储了structure.arm_id
的值然后,您可以使用以下步骤创建外键:
-- convert campaign_id to a proper integer
alter table bandit_pages
alter campaign_id type integer using campaign_id::int;
-- make campaign_id unique
alter table bandit_pages
add constraint unique_campaign_id unique (campaign_id);
--- create the foreign key
alter table structure
add constraint fk_structure_bandit_pages
foreign key (arm_id) references bandit_pages (campaign_id);