POSTGRESQL Foreign Key Referencing Primary Keys of two Different Tables

后端 未结 4 623
旧时难觅i
旧时难觅i 2020-12-02 10:24

I have two tables Books and Audiobooks, both of which have ISBN as their primary keys. I have a table writtenby that has an isbn attribute that has a foreign key constraint

4条回答
  •  情书的邮戳
    2020-12-02 11:10

    You could use table inheritance to kinda get the best of both worlds. Create the audiobook_writtenby and books_writtenby with an INHERITS clause referencing the writtenby table. The foreign keys could be defined at the child level as you describe, but you could still reference data at the higher level. (You could also do this with a view, but it sounds like inheritance might be cleaner in this case.)

    See the docs:

    http://www.postgresql.org/docs/current/interactive/sql-createtable.html

    http://www.postgresql.org/docs/current/interactive/tutorial-inheritance.html

    http://www.postgresql.org/docs/current/interactive/ddl-inherit.html

    Note that you will probably want to add a BEFORE INSERT trigger on the writtenby table if you do this.

提交回复
热议问题