Movatterモバイル変換


[0]ホーム

URL:



Facebook
Postgres Pro
Facebook
Downloads
PostgreSQL 9.4.1 Documentation
PrevUpChapter 3. Advanced FeaturesNext

3.6. Inheritance

Inheritance is a concept from object-oriented databases. It opens up interesting new possibilities of database design.

Let's create two tables: A tablecities and a tablecapitals. Naturally, capitals are also cities, so you want some way to show the capitals implicitly when you list all cities. If you're really clever you might invent some scheme like this:

CREATE TABLE capitals (  name       text,  population real,  altitude   int,    -- (in ft)  state      char(2));CREATE TABLE non_capitals (  name       text,  population real,  altitude   int     -- (in ft));CREATE VIEW cities AS  SELECT name, population, altitude FROM capitals    UNION  SELECT name, population, altitude FROM non_capitals;

This works OK as far as querying goes, but it gets ugly when you need to update several rows, for one thing.

A better solution is this:

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

In this case, a row ofcapitalsinherits all columns (name,population, andaltitude) from itsparent,cities. The type of the columnname istext, a nativePostgreSQL type for variable length character strings. State capitals have an extra column,state, that shows their state. InPostgreSQL, a table can inherit from zero or more other tables.

For example, the following query finds the names of all cities, including state capitals, that are located at an altitude over 500 feet:

SELECT name, altitude  FROM cities  WHERE altitude > 500;

which returns:

   name    | altitude-----------+---------- Las Vegas |     2174 Mariposa  |     1953 Madison   |      845(3 rows)

On the other hand, the following query finds all the cities that are not state capitals and are situated at an altitude over 500 feet:

SELECT name, altitude    FROM ONLY cities    WHERE altitude > 500;

   name    | altitude-----------+---------- Las Vegas |     2174 Mariposa  |     1953(2 rows)

Here theONLY beforecities indicates that the query should be run over only thecities table, and not tables belowcities in the inheritance hierarchy. Many of the commands that we have already discussed —SELECT,UPDATE, andDELETE — support thisONLY notation.

Note: Although inheritance is frequently useful, it has not been integrated with unique constraints or foreign keys, which limits its usefulness. SeeSection 5.8 for more detail.


PrevHomeNext
Window FunctionsUpConclusion
Go to PostgreSQL 9.4
By continuing to browse this website, you agree to the use of cookies. Go toPrivacy Policy.

[8]ページ先頭

©2009-2025 Movatter.jp