# 5.10.继承权

5.10.1. 警告

PostgreSQL实现了表继承,这对于数据库设计者来说是一个有用的工具。(SQL:1999及更高版本定义了一个类型继承功能,它在许多方面与这里描述的功能不同。)

让我们从一个例子开始:假设我们正在尝试为城市建立一个数据模型。每个州都有许多城市,但只有一个首府。我们希望能够迅速恢复任何特定州的首都。这可以通过创建两个表来实现,一个用于州首府,另一个用于非首府的城市。然而,当我们想要询问一个城市的数据时,不管它是否是首都,会发生什么?继承特性可以帮助解决这个问题。我们定义首都表,使其继承自城市:

CREATE TABLE cities (
    name            text,
    population      float,
    elevation       int     -- in feet
);

CREATE TABLE capitals (
    state           char(2)
) INHERITS (cities);

在这种情况下首都桌子继承其父表的所有列,城市.州首府也有一个额外的专栏,状态,这显示了他们的状态。

在PostgreSQL中,一个表可以从零个或多个其他表继承,查询可以引用表的所有行或表的所有行及其所有子表。后一种行为是默认行为。例如,以下查询将查找海拔超过500英尺的所有城市的名称,包括州首府:

SELECT name, elevation
    FROM cities
    WHERE elevation > 500;

给定PostgreSQL教程中的示例数据(请参见第2.1节),返回:

   name    | elevation
### 5.10.1. Caveats

 Note that not all SQL commands are able to work on inheritance hierarchies. Commands that are used for data querying, data modification, or schema modification (e.g., `SELECT`, `UPDATE`, `DELETE`, most variants of `ALTER TABLE`, but not `INSERT` or `ALTER TABLE ... RENAME`) typically default to including child tables and support the `ONLY` notation to exclude them. Commands that do database maintenance and tuning (e.g., `REINDEX`, `VACUUM`) typically only work on individual, physical tables and do not support recursing over inheritance hierarchies. The respective behavior of each individual command is documented in its reference page ([SQL Commands](sql-commands.html)).

 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:

* If we declared `cities`.`name` to be `UNIQUE` or a `PRIMARY KEY`, this would not stop the `capitals` table from having rows with names duplicating rows in `cities`. And those duplicate rows would by default show up in queries from `cities`. In fact, by default `capitals` would have no unique constraint at all, and so could contain multiple rows with the same name. You could add a unique constraint to `capitals`, but this would not prevent duplication compared to `cities`.

* Similarly, if we were to specify that `cities`.`name` `REFERENCES` some other table, this constraint would not automatically propagate to `capitals`. In this case you could work around it by manually adding the same `REFERENCES` constraint to `capitals`.

* 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.

 Some functionality not implemented for inheritance hierarchies is implemented for declarative partitioning. Considerable care is needed in deciding whether partitioning with legacy inheritance is useful for your application.