我有一个标准的嵌套集模型,每个节点都有名称,lft和rgt属性。
我可以使用以下方法找到特定员工的上司:
SELECT P2.* FROM Personnel AS P1, Personnel AS P2 WHERE P1.lft BETWEEN P2.lft AND P2.rgt AND P1.name = "Bob" ORDER BY P2.lft
我还可以通过添加限制和偏移量来找到level2管理器:
SELECT P2.* FROM Personnel AS P1, Personnel AS P2 WHERE P1.lft BETWEEN P2.lft AND P2.rgt AND P1.name = "Bob" ORDER BY P2.lft LIMIT 2 OFFSET 1
在某些情况下,我可能有多个名为“鲍勃”的员工在不同的level2经理下工作。级别2管理员名称是唯一的。
我需要一个查询,该查询返回名为“ Susan”的level2经理的所有名为“ Bob”的员工。
编辑:我的查询只需要返回在“玛丽”下工作的“鲍勃”,因为他是唯一拥有名为“苏珊”的二级经理的鲍勃。
Big Boss / \ Brian Susan | | Susan Mary | | Bob Bob
将数字放入:
1 Big Boss 14 / \ 2 Brian 7 8 Susan 13 | | 3 Susan 6 9 Mary 12 | | 4 Bob 5 10 Bob 11
如果可以指定我们知道它的“ Susan”,8则:
8
SELECT employee.* FROM Personnel AS employee inner join Personnel AS manager on employee.lft BETWEEN manager.lft AND manager.rgt WHERE employee.name = 'Bob' and manager.name = 'Susan' and manager.lft = 8 ORDER BY employee.lft
否则,我认为您需要了解更多有关记录的信息,以指定您要说的是哪个经理。
select employee.* from Personnel employee inner join (SELECT node.name, node.lft, node.rgt, (COUNT(parent.name) - 1) AS depth FROM Personnel AS node inner join Personnel AS parent on node.lft BETWEEN parent.lft AND parent.rgt GROUP BY node.name, node.lft, node.rgt) as manager on employee.lft between manager.lft and manager.rgt where employee.name = 'bob' and manager.name = 'susan' and manager.depth = 1