WITH RECURSIVE r AS (SELECT * FROM [表] WHERE id = xxxunion ALLSELECT [表].* FROM [表], r WHERE [表].id = r.parent_id)SELECT * FROM r ORDER BY id; 递归向上查询数据…
网易新闻的盖楼乐趣多,某一天也想实现诸如网易新闻跟帖盖楼的功能,无奈技术不佳(基础不牢),网上搜索了资料才发现SQL查询方法有一种叫递归查询,整理如下: 一.查询出 id = 1 的所有子结点 with my1 as (select * from table where id = 1 union all select table.* from my1, table where my1.id = table.fatherId) select * from my1 结果包含1这条记录,如果不想包含,…
SQL递归查询(with cte as) with cte as( select Id,Pid,DeptName,0 as lvl from Department where Id = 2 union all select d.Id,d.Pid,d.DeptName,lvl+1 from cte c inner join Department d on c.Id = d.Pid)select * from cte 1 表结构 Id Pid …
比如表结构数据如下: Table:Tree ID Name ParentId 1 一级 0 2 二级 1 3 三级 2 4 四级 3 SQL SERVER 2005查询方法: //上查 with tmpTree as ( select * from Tree where Id=2 union all select p.* from tmpTree inner join Tree p on p.Id=tmpTree.ParentId ) select * from tmpTree //下查…