Chapter 9. Inheritance

Let's create two classes. The capitals class contains state capitals which are also cities. Naturally, the capitals class should inherit from cities.

2 つのクラスを作ってみます。capitals クラスは、cities(市)で もある州都についての情報を持ちます。当然のことに、capitals ク ラスは cities を継承しなければなりません。

CREATE TABLE cities (
    name            text,
    population      float,
    altitude        int            -- (in ft)
);

CREATE TABLE capitals (
    state           char2
) INHERITS (cities);
In this case, an instance of capitals inherits all attributes (name, population, and altitude) from its parent, cities. The type of the attribute name is text, a native Postgres type for variable length ASCII strings. The type of the attribute population is float, a native Postgres type for double precision floating point numbers. State capitals have an extra attribute, state, that shows their state. In Postgres, a class can inherit from zero or more other classes, and a query can reference either all instances of a class or all instances of a class plus all of its descendants. この場合、capitals のインスタンスは、その親である cities から 全ての属性 (name、population、altitude) を 継承 します。name 属性の型は、 Postgres 固有の 可変長 ASCII 文字列 用の text 型です。population 属性の型は、 Postgres 固有のダブル精度浮動小数点 数用の float 型です。州都はこの他の属性として、そ の州を示す state 属性を持ちます。 Postgres では、クラスは 0 個以上のク ラスを継承でき、問い合わせは、クラスの全インスタンス、または、 クラスとそれを継承する全てのインスタンスのどちらも参照できます。

Note: The inheritance hierarchy is a actually a directed acyclic graph.

継承の階層は実際には非循環性有向グラフです。

For example, the following query finds all the cities that are situated at an attitude of 500ft or higher: 例えば、以下の問い合わせは、標高 500ft 以上にある都市を全て探し 出します。 ※ attitude → altitude として訳
SELECT name, altitude
    FROM cities
    WHERE altitude > 500;

+----------+----------+
|name      | altitude |
+----------+----------+
|Las Vegas | 2174     |
+----------+----------+
|Mariposa  | 1953     |
+----------+----------+

On the other hand, to find the names of all cities, including state capitals, that are located at an altitude over 500ft, the query is:

一方、標高 500ft 以上にある都市を、州都も含んで、全て探し出す 場合の問い合わせは、以下のようになります。

SELECT c.name, c.altitude
    FROM cities* c
    WHERE c.altitude > 500;
which returns: これは以下を返します。
+----------+----------+
|name      | altitude |
+----------+----------+
|Las Vegas | 2174     |
+----------+----------+
|Mariposa  | 1953     |
+----------+----------+
|Madison   | 845      |
+----------+----------+
Here the "*" after cities indicates that the query should be run over cities and all classes below cities in the inheritance hierarchy. Many of the commands that we have already discussed -- select, update and delete -- support this "*" notation, as do others, like alter. ここで、cities の後ろの "*" は、問い合わせが cities と継承階層において cities より下にあるクラス全てに対して 実施されることを示します。既に説明済みの、 selectupdatedelete といったコマンドの多くはこの "*" 表記をサポートしています。 alter といった他のものも同様です。