Id,PId无限级结构,查询某个Id的所有下级或所有上级,使用WITH AS查询
查找Id为1所有的下级
/*查找Id为1所有的下级*/ WITH T AS( SELECT Id,PId,Name,0 L FROM User WHERE Id=1 UNION ALL SELECT U.Id,U.PId,U.Name,L+1 FROM User U INNER JOIN T ON U.PId=T.Id ) SELECT * FROM T
查找Id为100所有的上级
/*查找Id为100所有的上级*/ WITH T AS( SELECT Id,PId,Name,0 L FROM User WHERE Id=100 UNION ALL SELECT U.Id,U.PId,U.Name,L+1 FROM User U INNER JOIN T ON U.Id=T.PId ) SELECT * FROM T