开发者

Should I add a type column to design inheritance in postgreSQL?

I am planning to create a web application using spring/hibernate.

How should I design my postgresql database in order to support inheritance?

Assume that I have the following tables: super_table, sub_table_1, sub_table_2.

Then sub_table_1 and subtable_2 would inherit super_table.

Should I add a type column (like a char or int) so that I would know

if the row in super_table is sub_table_1 or sub_table开发者_如何学运维_2?

Please advise. Thanks.


Sure you can do this for example to enforce that only one sub table can reference a given row:

CREATE TABLE Super_Table (
  super_id SERIAL PRIMARY KEY,
  sub_type CHAR(1) NOT NULL,
  UNIQUE KEY (super_id, sub_type) 
);

CREATE TABLE Sub_Table_A (
  super_id PRIMARY KEY,
  sub_type CHAR(1) NOT NULL,
  CHECK (sub_type = 'A'),
  FOREIGN KEY (super_id, sub_type) REFERENCES Super_Table (super_id, sub_type)
);

CREATE TABLE Sub_Table_B (
  super_id PRIMARY KEY,
  sub_type CHAR(1) NOT NULL,
  CHECK (sub_type = 'B'),
  FOREIGN KEY (super_id, sub_type) REFERENCES Super_Table (super_id, sub_type)
);

Now there is no way a row in Super_Table can be referenced by a row in both sub tables. The row in Super_Table must have either 'A' or 'B' and so only one of the sub tables can satisfy the foreign key reference.


Re your comment:

My understanding is that the current PostgreSQL implementation of INHERITS allows a number of anomalies related to indexes, unique constaints, and foreign key constraints. Using this feature is tricky and error-prone.

Basically, because indexes exist only over a single table, if you have a unique constraint on your parent table then how can it enforce that uniqueness over the parent and all of its children? The children could insert values into their tables that already exist in the parent, or the parent could insert a value that already exists in one of the children.

Likewise foreign keys cannot reference the parent table and/or its children because it's ambiguous which row is referenced if multiple rows can exist in parent/children with the same primary key or unique value.

These are known and unresolved limitations of INHERITS in PostgreSQL. The design I showed above resolves the problem for primary key, but not for secondary unique keys.

http://archives.postgresql.org/pgsql-hackers/2010-05/msg00285.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜