| Документация по PostgreSQL 9.4.1 | |||
|---|---|---|---|
| Пред. | Уровень выше | Глава 3. Расширенные возможности | След. |
3.6. Наследование
Наследование — это концепция, взятая из объектно-ориентированных баз данных. Она открывает множество интересных возможностей при проектировании баз данных.
Давайте создадим две таблицы: cities (города) и capitals (столицы штатов). Естественно, столицы штатов также являются городами, поэтому нам нужно явным образом добавлять их в результат, когда мы хотим просмотреть все города. Если вы проявите смекалку, вы можете предложить, например, такое решение:
CREATE TABLE capitals (
name text,
population real,
altitude int, -- (высота в футах)
state char(2)
);
CREATE TABLE non_capitals (
name text,
population real,
altitude int -- (высота в футах)
);
CREATE VIEW cities AS
SELECT name, population, altitude FROM capitals
UNION
SELECT name, population, altitude FROM non_capitals;Оно может устраивать, пока мы извлекаем данные, но если нам потребуется изменить несколько строк, это будет выглядеть некрасиво.
Поэтому есть лучшее решение:
CREATE TABLE cities ( name text, population real, altitude int -- (высота в футах) ); CREATE TABLE capitals ( state char(2) ) INHERITS (cities);
В данном случае строка таблицы capitals наследует все колонки (name, population и altitude) от родительской таблицы cities. Колонка name имеет тип text, собственный тип PostgreSQL для текстовых строк переменной длины. А в таблицу столиц добавлена дополнительная колонка state, в которой будет указан штат. В PostgreSQL таблица может наследоваться от нуля или нескольких других таблиц.
Например, следующий запрос выведет названия всех городов, включая столицы, находящихся выше 500 футов над уровнем моря:
SELECT name, altitude FROM cities WHERE altitude > 500;
Результат его выполнения:
name | altitude -----------+---------- Las Vegas | 2174 Mariposa | 1953 Madison | 845 (3 rows)
А следующий запрос находит все города, которые не являются столицами штатов, но также находятся выше 500 футов:
SELECT name, altitude
FROM ONLY cities
WHERE altitude > 500;name | altitude -----------+---------- Las Vegas | 2174 Mariposa | 1953 (2 rows)
Здесь слово ONLY перед названием таблицы cities указывает, что запрос следует выполнять только для строк таблицы cities, не включая таблицы, унаследованные от cities. Многие операторы, которые мы уже обсудили — SELECT, UPDATE и DELETE — поддерживают указание ONLY.
Замечание: Хотя наследование часто бывает полезно, оно не интегрировано с ограничениями уникальности и внешними ключами, что ограничивает его применимость. Подробнее это описывается в Разделе 5.8.
| Пред. | Начало | След. |
| Оконные функции | Уровень выше | Заключение |
| PostgreSQL 9.4.1 Documentation | |||
|---|---|---|---|
| Prev | Up | Chapter 3. Advanced Features | Next |
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 table cities and a table capitals. 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 of capitals inherits all columns (name, population, and altitude) from its parent, cities. The type of the column name is text, a native PostgreSQL type for variable length character strings. State capitals have an extra column, state, that shows their state. In PostgreSQL, 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 the ONLY before cities indicates that the query should be run over only the cities table, and not tables below cities in the inheritance hierarchy. Many of the commands that we have already discussed — SELECT, UPDATE, and DELETE — support this ONLY notation.
Note: Although inheritance is frequently useful, it has not been integrated with unique constraints or foreign keys, which limits its usefulness. See Section 5.8 for more detail.