0

在此处输入图像描述

我想在数据库中为应用程序创建给定的公司结构,并希望根据该结构遍历员工详细信息。下面给出的问题。

当员工登录系统时,他应该能够看到在他的级别工作的员工的详细信息。比如“主管B”登录系统,应该可以看到员工A、员工B、员工C、员工C的下属人员的详细信息。

同时,C 员工向 C 组长汇报,C 组长只能查看 C 员工的详细信息,不能查看他的下级员工。这意味着,当 C 组长登录时,他可以查看他的子员工和员工 C。

但是部门主管 D 可以查看员工 C 的详细信息和他的子员工的详细信息,因为他具有对分支机构的完全访问权限,从员工 C 开始。这意味着他可以查看他的子员工以及员工 C 和他的子员工。

谁能帮我实现这个结构和数据库中的访问级别以及如何以有效的方式查询它们?

4

2 回答 2

3

解决这种层次结构遍历问题的常用方法是使用一种称为访问数的技术,我在对这个问题的回答中对此进行了详细描述。使用访问编号,您可以轻松找到层次结构中任何给定节点下方的所有节点的列表。

请注意,您仍将使用员工表上的内卷外键记录每个员工的直接报告上级。

对于您的情况,您还有常规报告层次结构之外的虚线报告(员工 C 到科长 C)。这意味着您将需要两种方法。第一种是使用访问次数进行定期报告,经理可以看到他们所有的直接和间接报告,然后是其他用于虚线报告的内容。

您似乎有两种用于虚线报告的规则。一些虚线主管可以看到下属,而另一些只能看到他们的虚线直属下属。由于人们可以有多个虚线主管,因此需要添加一个交集表来记录这些虚线关系。该交集表还可以包括标志属性,该标志属性指示虚线主管是否能够看到唯一的直接虚线下属或那个人和他们的所有下属。

无论哪种方式,虚线关系都直接记录在员工与其主管之间,而常规报告关系(可能是间接的)由访问人数管理。

于 2012-08-15T12:12:36.927 回答
0

您需要几个关于员工的自联接表。一个代表主管与员工的关系。第二个代表员工之间的同伴关系。

这是 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';

于 2012-08-15T12:41:04.693 回答