我有一个名为people的表,以及一个名为position_hIErarchy的表. people表有一个唯一的ID uperson_ID和我们称为pcn的位置ID和一个启用的标志(因为当有人离开并被替换时,他们的替换获得相同的pcn). position_hIErarchy具有列pcn,另一列reports_to是层次结构中位于它们之上的人的pcn.我想要做的是给一个人的uperson_ID,并在层次结构中找到他们上面的人的所有uperson_ID,和/或给一个uperson_ID和另一个人的uperson_ID,并告诉第二个人是否拥有超过第一个人的监督职位.
该公司的总裁被指出是因为他们的pcn与他们的report_to相同. (不是我的决定 – 我会使用null reports_to)
到目前为止我想出的是:
with recursive parents (uperson_ID,pcn,reports_to) as( select p1.uperson_ID,ph1.pcn,ph1.reports_to from people p1 join position_hIErarchy ph1 on ph1.pcn = p1.pcn where reports_to != ph1.pcn and active_revoke_flag = '0' union all select p2.uperson_ID,ph2.pcn,ph2.reports_to from people p2 join position_hIErarchy ph2 on p2.pcn = ph2.pcn join parents pp on pp.pcn = ph2.reports_to)select parents.* from parents where uperson_ID = 'aaa3644';
但是返回5行,使用相同的uperson_ID,pcn和reports_to(这似乎是正确的行数,但我希望每个级别的主管的uperson_ID.我觉得我缺少一些非常基本的东西,我可能会打耳光当你告诉我我做错了什么时,我的脑袋.
我做了什么
基于Erwin Brandstetter’s answer,我修复了一些事情(主要是因为我没有弄清楚active_revoke_flag在哪个表中)并提出了:
with recursive p as ( select pcn,reports_to from position_hIErarchy where pcn = (SELECT pcn FROM people WHERE uperson_ID = 'aaa3644') union all select ph2.pcn,ph2.reports_to from p join position_hIErarchy ph2 ON ph2.pcn = p.reports_to AND p.pcn != p.reports_to)select p2.uperson_ID,p2.active_revoke_flag,p.*from pjoin people p2 USING (pcn)where p2.active_revoke_flag = '0';我会尝试这种自下而上的方法,从感兴趣的人开始,然后继续努力:
with recursive p as ( select p1.uperson_ID,p1.pcn,ph1.reports_to from people p1 join position_hIErarchy ph1 USING (pcn) where ph1.active_revoke_flag = '0' and p1.uperson_ID = 'aaa3644' union all select p2.uperson_ID,p2.pcn,ph2.reports_to from p join position_hIErarchy ph2 ON ph2.pcn = p.reports_to AND ph2.active_revoke_flag = '0' join people p2 ON p2.pcn = ph2.pcn)select * from p;
或者,更快,因为我们只加入一次人:
with recursive p as ( select pcn,reports_to from position_hIErarchy where active_revoke_flag = '0' and pcn = (SELECT pcn FROM person WHERE uperson_ID = 'aaa3644') union all select ph2.pcn,ph2.reports_to from p join position_hIErarchy ph2 ON ph2.pcn = p.reports_to AND ph2.active_revoke_flag = '0')select p2.uperson_ID,p.*from pjoin people p2 USING (pcn); -- assuming pcn is unique in table person
暂且不说:我确实发现你的设计有重复的pcn有点可疑.
总结以上是内存溢出为你收集整理的postgresql – 查找员工的所有主管全部内容,希望文章能够帮你解决postgresql – 查找员工的所有主管所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)