如何在一个表中使用多个分层的FK?

时间:2018-11-30 17:18:56

标签: foreign-keys pgadmin-4 postgresql-11

我有两个表以1:M的关系相互关联:parentchild。 我已经通过使用外键约束将parent_id表中的child列限制为仅匹配parent的表ID值。现在,我希望第三个表(称为another_table)具有两个FK列,它们引用idparent表中的child列。

如何将第三张表中的child_id FK列限制为child表中与parent_id值匹配的值?

enter image description here

编辑


E.G:如前所述,我有三个表-parentchildanother_table。他们的内容如下:

SELECT * FROM public.parent

id  name
1   A
2   B
3   C

SELECT * FROM public.child

id name parent_id 
1   A1  1
2   A2  1
3   A3  1
4   B1  2
5   C1  3
6   C2  3

SELECT * FROM public.another_table

enter image description here

我想(同时)在数据库结构中找到一种方法,以防止在第三表的child_id列中插入或更新不符合child的值的表数据。

1 个答案:

答案 0 :(得分:1)

由于父级已链接到子级,因此子级具有父级链接。您不需要将父母和孩子都链接到孩子的孩子。您只需要将孩子的孩子链接到已经有父母的孩子。

    Parent
      /\
child1  child2
           /\
   pc_child  pc_child2

Visual Explanation

相关问题