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