我构建了一个完成这项工作的存储过程。这从一个主管 id 开始,并找到所有的孩子和他们的孩子。小心循环关系!
假设:Employee表有PID(人)和SupID(主管)
Emailtable 有 PID、PersonName、Email、Nodelevel (int),一开始是空的。
调用 Nodeup(1,SupervisorID)(参数 IN curnode int,IN supid int)
BEGIN
#Routine body goes here...
declare newnode int;
if curnode = 1 then
insert emailtable (pid,personname,email,nodelevel) select pid,personname,email,1 from employees where pid = superid;
end if;
insert emailtable(personname,pid,email,nodelevel) select personname,pid,email,curnode+1
from employees where supid in (select pid from emailtable where curnode = emailtable.nodelevel);
set newnode = (select max(nodelevel) from emailtable);
if newnode > curnode then
call nodeup(Newnode,0);
end if;
END