了解 Postgres 中的继承;为什么在 insert/update 命令中输入 "fails"

understanding an inheritance in Postgres; why key "fails" in insert/update command

(一张图片,千言万语) 我做了一些在他们之间继承的 table。 (人) 然后分配 child table(地址),并将其仅关联到“base”table(人)。 当尝试在子 table 中插入时,记录与继承 table 相关,插入语句失败,因为主 table 中没有键。 当我在后代 tables 中插入记录时,记录在基础 table 中可用(因此,恕我直言,在继承的 tables 中应该是 visible/accessible)。 请查看所附图片。显然做错了什么或没有得到一些观点...... 先谢谢你了!

抱歉,这就是 Postgres table 继承的工作原理。 5.10.1 Caveats 说明。

A serious limitation of the inheritance feature is that indexes (including unique constraints) and foreign key constraints only apply to single tables, not to their inheritance children. This is true on both the referencing and referenced sides of a foreign key constraint. Thus, in the terms of the above example:

Specifying that another table's column REFERENCES cities(name) would allow the other table to contain city names, but not capital names. There is no good workaround for this case.

在他们的例子中,capitals 继承自 cities,就像 organization_employees 继承自 person。如果 person_address REFERENCES person(idt_person) 它不会在 organization_employees.

中看到条目

继承并不像看起来那么有用,也不是避免连接的方法。使用带有一些额外列的连接 table 可以更好地完成此操作。不清楚为什么一个组织会继承一个人。

person
  id bigserial primary key
  name text not null
  verified boolean not null default false
  vat_nr text
  foto bytea

# An organization is not a person
organization
  id bigserial not null
  name text not null

# Joins a person with an organization
# Stores information about that relationship
organization_employee
  person_id bigint not null references person(id)
  organization_id bigint not null references organization(id)
  usr text
  pwd text

# Get each employee, their name, and their org's name.
select
  person.name
  organization.name
from
  organization_employee
join person on person_id = person.id
join organization on organization_id = organization.id
  • 主键使用bigserial(bigint),20亿来得比你想象的还要快
  • 不要在模式中加入任意的业务规则,比如名称可以有多长。您不会通过限制来保存任何 space,并且每次业务规则更改时,您都必须更改架构。使用文本类型。在应用程序中强制执行任意限制或作为约束。
  • idt_table_name 主键使得长的、不一致的列名难以猜测。为什么person_address的主键不是idt_person_address?为什么organization_employee的主键是idt_person?你无法一眼看出哪个是主键,哪个是外键。您仍然需要在列名前添加以消除歧义;例如,如果您加入 person_address 的人,您需要 person.idt_personperson_address.idt_person。混乱和多余。 id(或 idt,如果您愿意)使主键是什么变得显而易见,并清楚地将其与 table_id(或 idt_table)外键区分开来。 SQL已经有办法解决歧义:person.id.