# 3.6.继承权

继承是一个来自面向对象数据库的概念。它为数据库设计开辟了有趣的新可能性。

让我们创建两个表:一个表城市还有一张桌子首都.当然,首府也是城市,所以当你列出所有城市时,你需要某种方式来隐式显示首府。如果你真的很聪明,你可能会发明这样的计划:

CREATE TABLE capitals (
  name       text,
  population real,
  elevation  int,    -- (in ft)
  state      char(2)
);

CREATE TABLE non_capitals (
  name       text,
  population real,
  elevation  int     -- (in ft)
);

CREATE VIEW cities AS
  SELECT name, population, elevation FROM capitals
    UNION
  SELECT name, population, elevation FROM non_capitals;

就查询而言,这是可行的,但当您需要更新几行时,它会变得很糟糕。

更好的解决方案是:

CREATE TABLE cities (
  name       text,
  population real,
  elevation  int     -- (in ft)
);

CREATE TABLE capitals (
  state      char(2) UNIQUE NOT NULL
) INHERITS (cities);

在这种情况下,一排首都 继承所有栏目(名称,人口高程)从它的父母亲, 城市.列的类型名称文本,一种用于可变长度字符串的本机PostgreSQL类型。这个首都表中有一个附加列,状态,显示其州缩写。在PostgreSQL中,一个表可以从零个或多个其他表继承。

例如,以下查询将查找海拔超过500英尺的所有城市的名称,包括州首府:

SELECT name, elevation
  FROM cities
  WHERE elevation > 500;

返回:

   name    | elevation
### Note

 Although inheritance is frequently useful, it has not been integrated with unique constraints or foreign keys, which limits its usefulness. See [Section 5.10](ddl-inherit.html) for more detail.