SQL语句查询出父节点下的所有子节点
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL语句查询出父节点下的所有子节点相关的知识,希望对你有一定的参考价值。
SQL语句查询出父节点下的所有子节点
id username parentid
1 user1
2 user2 1
3 user3 2
4 user4 1
parentId是父节点,
如用SQL查询出user1 及子节点user2、user4
create table ##tmp_users (id int, username nvarchar(255), parentid int )
declare @ID int
select @ID=id from t_Users t where exists
(select * from t_Users t2 where t2.id=t.parentid and t2.username='user1')
exec AddSons @ID
select * from ##tmp_users
drop table ##tmp_users
--存储
create procedure AddSons @id int
as
if exists(select * from t_Users where parentid=@id)
begin
declare @tmp_ID int
declare cur cursor for
select id from t_Users where parentid=@id
open cur
fetch next from cur into @tmp_ID
while @@FETCH_STATUS=0
begin
insert into ##tmp_users
select * from t_Users t where id=@tmp_ID
if exists(select * from t_Users where parentid=@tmp_ID)
begin
exec AddSons @tmp_ID
end
fetch next from cur into @tmp_ID
end
close cur
DEALLOCATE cur
end
--递归调用,不知道是否想要这样 参考技术A SQL> select * from new;
ID USERNAME PARENTID
---------- ---------- ----------
1 user1
2 user2 1
3 user3 2
4 user4 1
SQL> select sys_connect_by_path(username,'>') "Path"
2 from new
3 start with id=1
4 connect by prior id=parentid;
Path
--------------------------------------------------------------------------------
>user1
>user1>user2
>user1>user2>user3
>user1>user4 参考技术B select b.username from tablename a right outer join tablename b on a.id = b.pid where b.parentid = 1 or b.parentid is null; 参考技术C 是直接字节点还是包括子节点的字节点。。?追问
直接子节点的
追答select * from tb where id = 1 or parentid = 120170411-oracle 查询指定节点下的所有子节点包括直到叶子节点
查询父节点
SELECT * FROM r_org org START WITH org.org_code = \'6199840Q\' CONNECT BY PRIOR PARENT_ID = ID;
select * from r_org org where org.org_code = \'61000089\') connect by prior org.id = org.parent_id
select * from emp e start with e.empno=7839
connect by prior e.empno=e.mgr
以上是关于SQL语句查询出父节点下的所有子节点的主要内容,如果未能解决你的问题,请参考以下文章
一条sql语句顺序查询出父类的所有子类 如下图:用的是sql Server 2008
SQL查询父节点下的所有子节点(包括子节点下的子节点,无限子节点)