SELECT P2.emp,SUM(S1.salary)FROM Personnel AS P1, Personnel AS P2, Salaries AS S1WHERE P1.lft BETWEEN P2.lftAND P2.rgtAND P1.emp = S1.empGROUP BY P2.emp;
在邻接表模型中,你必须使用游标来完成这个功能。
找到每个节点的级别,以便你可以将树打印为缩进列表。
SELECTCOUNT(P2.emp) AS indentation, P1.empFROM Personnel AS P1, Personnel AS P2WHERE P1.lft BETWEEN P2.lftAND P2.rgtGROUP BY P1.empORDER BY P1.lft;
CREATETABLETree(emp CHAR(10) NOT NULL,boss CHAR(10));INSERT INTO TreeSELECT emp, boss FROM Personnel;-- Stack starts empty, will holds the nested set modelCREATETABLEStack(stack_top INTEGERNOT NULL,emp CHAR(10) NOT NULL,lft INTEGER,rgt INTEGER);BEGINATOMICDECLAREcounterINTEGER;DECLARE max_counter INTEGER;DECLARE current_top INTEGER;SETcounter=2;SET max_counter =2* (SELECTCOUNT(*)FROM Tree);SET current_top =1;INSERT INTO StackSELECT1, emp,1,NULLFROM TreeWHERE boss ISNULL;DELETEFROM TreeWHERE boss ISNULL;WHILEcounter<= (max_counter -2)LOOPIFEXISTS (SELECT*FROM Stack AS S1, Tree AS T1WHERE S1.emp = T1.bossAND S1.stack_top = current_top) THENBEGIN-- push when top has subordinates, set lft valueINSERT INTO StackSELECT (current_top +1), MIN(T1.emp), counter, NULLFROM Stack AS S1, Tree AS T1WHERE S1.emp = T1.bossAND S1.stack_top = current_top;DELETEFROM TreeWHERE emp = (SELECT empFROM StackWHERE stack_top = current_top +1);SETcounter=counter+1;SET current_top = current_top +1;ENDELSEBEGIN-- pop the stack and set rgt valueUPDATE StackSET rgt =counter, stack_top =- stack_top -- pops the stackWHERE stack_top = current_topSETcounter=counter+1;SET current_top = current_top -1;ENDIF;ENDLOOP;END;