您需要几个关于员工的自联接表。一个代表主管与员工的关系。第二个代表员工之间的同伴关系。
这是 PostgreSQL 的 SQL
如果存在 stackoverflow 级联,则删除模式;
创建架构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
从 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';