Foreign keys + table inheritance in PostgreSQL?

后端 未结 3 944
囚心锁ツ
囚心锁ツ 2020-12-30 22:05

I have three tables: organization, organization_teams and org_users. Here organization_teams is inherited from orga

相关标签:
3条回答
  • 2020-12-30 22:14

    Completely agree with @Craig Ringer, we can't use foreign keys along with inheritance.

    But if we are sure that we are going to insert correct data, and we want to use foreign key in org_users, we can do one thing.

    We can create a child table of org_users say org_users_child (with no foreign key) as below

    CREATE TABLE org_users_child () INHERITS (org_users);
    

    Now we can insert data in this child table.

    Now if we query over org_users table, we can find desired results.

    0 讨论(0)
  • 2020-12-30 22:24

    The only workaround i have found is:

    1. create function returning trigger for checking existence of some id in inherited table
    2. create a constraint trigger instead of FK
    0 讨论(0)
  • 2020-12-30 22:36

    It's covered in the user manual.

    The short version: you can use foreign keys, or table inheritance, but not both. This isn't inherently impossible, it's just that it's technically quite difficult to implement unique indexes that span inherited tables in PostgreSQL in a fast, reliable manner. Without that, you can't have a useful foreign key. Nobody's successfully implemented it well enough for a patch adding support to be accepted into PostgreSQL yet.

    A foreign key can point to a table that is part of an inheritance hierarchy, but it'll only find rows in that table exactly. Not in any parent or child tables. To see which rows the foreign key sees, do a SELECT * FROM ONLY thetable. The ONLY keyword means "ignoring inheritance" and that's what the foreign key lookup will do.

    0 讨论(0)
提交回复
热议问题