日期:2014-05-17  浏览次数:21066 次

关于组织机构和人员表的设计、查询问题
某单位的组织机构为树形结构:集团》公司》子公司》部门》班组。

组织机构表Dept设计如下:
DeptId:组织机构id
DeptName:组织机构名称
ParentId:上级组织机构id

人员表Emp设计如下:
EmpId:人员Id
EmpName:姓名
DeptId:所属组织机构id

请问:
1、如何查询某级机构管辖的所有人员,即根据某级组织机构的DeptId,得到其本身和其下属的各级机构的人员?
2、如何查询某人员的工作部门全称,即根据某人员的EmpId,得到类似“XX公司XX子公司XX部门XX班组”的完整路径?
------解决方案--------------------
给你一个关键字,自己百度一下把弟弟
start with
connect by prio

oracle树形结构,你的需求很简单 一句sql的事儿。
------解决方案--------------------
在dept表上用connect by可以解决。
1)start with deptid = 某级组织机构的DeptId, 可以找到下属的所有机构
2) sys_connect_by_path(deptname, '/')
------解决方案--------------------
with dept as(
   select 1 deptId,'集团' deptName,null parentid from dual union all
   select 2,'北京公司',1 from dual union all
   select 3,'海淀分公司',2 from dual union all
   select 4,'财务部',3 from dual union all
   select 5,'市场组',4 from dual union all
   select 6,'销售组',4 from dual
)


,emp as(
   select 1 empid,'李01' empname,4 deptid from dual union all
   select 2 empid,'李02' empname,5 from dual union all
   select 3,'张01',5 from dual
)
--1
select * from emp p  where exists(

select * from dept t start with deptId = 4 connect by prior deptid = parentid and p.deptid = t.deptid
); 

--2
select e.empid,p.deptemp 
------解决方案--------------------
'/' 
------解决方案--------------------
 empname ename from 
(select * from emp where empid = 2) e,

(select deptId,deptname,sys_connect_by_path(deptname,'/') deptemp 
from dept start with deptId = 1 connect by prior deptid = parentid) p where e.deptid = p.deptid;


关键在

引用:
给你一个关键字,自己百度一下把弟弟
start with
connect by prio

oracle树形结构,你的需求很简单 一句sql的事儿。



up