Postgres table 继承:从 parent 移动到 child,反之亦然

Postgres table inheritance: move from parent to child and vice versa

我想知道如何在 PostgreSQL (9.4) 中轻松地在 parent table 和它的 child table 之间移动数据,反之亦然。

假设我设置了以下数据库示例:

DROP TABLE IF EXISTS employee CASCADE;
DROP TABLE IF EXISTS director CASCADE;

CREATE TABLE employee(
id SERIAL PRIMARY KEY NOT NULL,
name VARCHAR(255) NOT NULL,
surname VARCHAR(255) NOT NULL,
employment_date DATE NOT NULL DEFAULT CURRENT_DATE
);

CREATE TABLE director(
director_id SERIAL PRIMARY KEY NOT NULL,
secretary_id INT4 REFERENCES employee(id),
extra_legal_benefits VARCHAR(255) ARRAY
) inherits (employee);

INSERT INTO employee(name, surname)
VALUES ('Alice', 'Alisson');

INSERT INTO employee(name, surname)
VALUES ('Bob', 'Bobson');

INSERT INTO employee(name, surname)
VALUES ('Carol', 'Clarckson');

INSERT INTO director(name, surname, secretary_id, extra_legal_benefits)
VALUES ('David', 'Davidson', 1, '{car, travel expenses}');

如何将其中一名员工提拔(调动)为主管 table(不得再出现在 parent 中)?

我怎样才能将其中一名董事降级(调动)回员工 table(不得再出现在 child 中)?

晋升员工:

with deleted as (
  delete from only employee 
  where name = 'Carol'
  returning *
)
insert into director (name, surname, secretary_id, extra_legal_benefits)
select name, surname, null, '{flight}'
from deleted;

但是:

must no longer appear in the parent

根据定义,子 table 中的任何行在父 table 中可用。如果在从员工 table:

中选择时使用谓词 only,则只能 "hide" 这些行
select *
from only employee;

以上不会显示兼任董事的员工。普通 select * from employee 然而 显示所有名称(但您无法区分它们 - 这就是继承的本质)。


降级主管:

with deleted as (
  delete from only director 
  where name = 'David'
  returning *
)
insert into employee (name, surname)
select name, surname
from deleted;

但老实说,我可能会通过在员工实体上添加一个列(如 positionrole)来建模,而不是使用继承。甚至是与 position(或 role)实体的多对多关系,因为员工具有多个角色的情况并不少见,例如在不同的部门、团队或其他环境中。