问题
I have a standard nested set model with each node having name, lft & rgt attributes.
I can find the superiors of a specific employee using:
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
I can also find the level2 manager by adding limit & offset:
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
In some situations I may have multiple employees called "Bob" working under different level2 managers. The level2 manager names are unique.
I need a query that returns all the employees called "Bob" for the level2 manager called "Susan".
Edit: My query needs to return only the "Bob that works under "Mary" as he is the only one with a level2 manager called "Susan".
Big Boss
/ \
Brian Susan
| |
Susan Mary
| |
Bob Bob
回答1:
Putting the numbers in:
1 Big Boss 14
/ \
2 Brian 7 8 Susan 13
| |
3 Susan 6 9 Mary 12
| |
4 Bob 5 10 Bob 11
If we can specify that we know that its the "Susan" at 8
then:
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
Otherwise, I think you need to know more about the record to specify which manager you're speaking of.
EDIT: Making the query a bit more complicated, I've calculated depth using suggestions from this article. The fiddle for this is working as well.
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
来源:https://stackoverflow.com/questions/26983613/how-to-locate-a-specific-child-of-a-specific-level2-node-in-a-nested-set