SQL语句查询出父节点下的所有子节点
SQL语句查询出父节点下的所有子节点idusernameparentid1user12user213user324user41parentId是父节点,如用SQL查询出u...
SQL语句查询出父节点下的所有子节点
id username parentid
1 user1
2 user2 1
3 user3 2
4 user4 1
parentId是父节点,
如用SQL查询出user1 及子节点user2、user4 展开
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
--递归调用,不知道是否想要这样
展开全部
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
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
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
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;
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
是直接字节点还是包括子节点的字节点。。?
追问
直接子节点的
追答
select * from tb where id = 1 or parentid = 1
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询