従業員にいくつかの自己結合テーブルが必要です。1 つは上司と従業員の関係を表します。2 つ目は、従業員間のピア関係を表します。
これがPostgreSQLのSQLです
stackoverflow カスケードが存在する場合はスキーマを削除します。
スキーマのスタックオーバーフローを作成します。
search_path を stackoverflow、public に設定します。
テーブルの従業員を作成する
(
id serial not null unique,
name text not null unique,
title text not null,
primary key ( id )
);
テーブル レポートの作成
(
supervisorid integer not null references employee ( id ) on delete cascade ,
subordinateid integer not null references employee ( id )
check ( supervisorid != subordinateid ),
unique ( supervisorid, subordinateid ),
unique( subordinateid )
);
テーブル ピアの作成
(
supervisorid integer not null references employee ( id ) on delete cascade ,
peerid integer not null references employee ( id )
check ( supervisorid != peerid ),
unique ( supervisorid, peerid )
);
直属の部下を次のように作成または置換
select supervisor.id as "supervisor id",
supervisor.name as "supervisor name",
reporting.id as "employee id", reporting.name as "employee name"
from
employee supervisor, employee reporting , reports
where
supervisor.id = reports.supervisorid
and reporting.id = reports.subordinateid;
create or replace view peerreports as
select * from directreports、peer、employee
where
employee.id = peer.peerid
and peer.supervisorid = directreports."supervisor id";
従業員に挿入 (名前、役職)
values ( 'c head', 'c head'),
( 'd head', 'd head'),
('c emp1', 'c emp1' ) ,
('c emp2', 'c emp2' ) ;
insert into reports
select employee.id as "supervisorid",
reportsto.id as "subordinateid"
from employee, employee reportsto
where employee.name = 'c head'
and reportsto.name in ('c emp1', 'c emp2' )
and reportsto.name != employee.name ;
insert into peer
select employee.id as "supervisorid",
peerto.id as "peer.peerid"
from employee, employee peerto
where employee.name = 'c head' and peerto.name = 'd head'
and employee.id != peerto.id;
典型的なクエリは次のとおりです
従業員から * を選択します。
レポートから * を選択します。
直属の部下から * を選択します。
ピアから * を選択します。
select * from peerreports, employee where employee.name= 'd head';