WITH AS查询:无限级结构SQL查询所有下级和上级

2020年1月15日17:12:31 发表评论 129 views

Id,PId无限级结构,查询某个Id的所有下级或所有上级,使用WITH AS查询:

/*查找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所有的上级*/
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

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: