需要将 FK 约束添加到 table,同时保持现有数据与另一个 table 的关系

Need to add FK constraint to table, while keeping existing data's relation to another table

我目前有这个架构,以及两个 table 中的一些数据:

       animal table                   pet_accessories table
+---------------+---------+   +-----------------------+-----------+
|  animal_key   |   type  |   |  pet_accessories_key  |   animal  |
+---------------+---------+   +-----------------------+-----------+
|      1        |   Dog   |   |           1           |   Dog     |
|      2        |   Cat   |   |           2           |   Bird    |
|      3        |   Bird  |   |           3           |   Cat     |   
+---------------+---------+   |           4           |   Cat     | 
                              +-----------------------+-----------+

但需要添加 table 之间的关系,并使用 FK 约束从 pet_accessories 到动物 table。最终,这就是我需要的:

       animal table                   pet_accessories table
+---------------+---------+   +-----------------------+---------------+
|  animal_key   |   type  |   |  pet_accessories_key  |   animal_key  |
+---------------+---------+   +-----------------------+---------------+
|      1        |   Dog   |   |           1           |       1       |
|      2        |   Cat   |   |           2           |       3       |
|      3        |   Bird  |   |           3           |       2       |   
+---------------+---------+   |           4           |       2       | 
                              +-----------------------+---------------+

我已经尝试向我现有的 pet_accessories table 添加一个新的键列,但是在正确设置这个 animal_key 的逻辑上遇到了问题:

+-----------------------+-----------+--------------+
|  pet_accessories_key  |   animal  |  animal_key  |
+-----------------------+-----------+--------------+
|           1           |   Dog     |              |
|           2           |   Bird    |              |
|           3           |   Cat     |              | 
|           4           |   Cat     |              |
+-----------------------+-----------+--------------+ 

我知道 SQL 主要是一种面向集合的语言 - 在其中使用循环通常不是一个好主意。我还读到我可能会使用游标,尽管我对它们不太熟悉。

问题是,遍历 pet_accessories.animal 中的数据并与 animals.type 进行比较的最佳方法是什么,以便我最终可以设置 pet_accessories.animal_key = animal.animal_key所有现有 pet_accessories 条记录?换句话说,我如何:

for each record in pet_accessories
  for each record in animal
    if pet_accessories.animal == animal.type
      then pet_accessories.animal_key = animal_animal_key

首先,添加列:

alter table pet_accessories add animal_key integer;

然后,更新列:

update pa
    set animal_key = a.animal_key
    from pet_accessories pa join
         animals a
         on pa.animal = a.type;

然后,检查以确保一切都是您想要的。

然后,删除旧列:

alter table pet_accessories drop column animal;

然后添加外键约束:

alter table add constraint fk_animal_key
    foreign key (animal_key) references animal(animal_key);