一个取根父级的问题!!!!!!!!!!!!

qiudong_5210 2011-06-13 04:47:01

Id LId
1 0
2 1
3 2
4 3
5 0
6 5

-- 输入的参数是Id,怎么返回他的根父级啊
--比如:输入4,返回1,输入3,返回1 输入6,返回5,输入5,返回5
...全文
121 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
huangwenquan123 2011-06-13
  • 打赏
  • 举报
回复

create table #tb(id int,LId int)
insert into #tb
select 1,0 union all
select 2,1 union all
select 3,2 union all
select 4,3 union all
select 5,0 union all
select 6,5

declare @ID int
set @ID=4
;with cte as(
select * from #tb where ID=@ID union all
select t.* from cte c inner join #tb t on t.id=c.lid
)
select top 1 id from cte order by id
/*
1
*/
huangwenquan123 2011-06-13
  • 打赏
  • 举报
回复
create table #tb(id int,LId int)
insert into #tb
select 1,0 union all
select 2,1 union all
select 3,2 union all
select 4,3 union all
select 5,0 union all
select 6,5

select * from #tb

declare @ID int
set @ID=5
;with cte as(
select * from #tb where ID=@ID union all
select t.* from cte c inner join #tb t on t.id=c.lid
)
select top 1 id from cte order by id
wanghui0380 2011-06-13
  • 打赏
  • 举报
回复
需要向上递归

ps:这种表结构虽然能表达树关系,但是实际使用中往往需要向上,或向下递归。所以我们通常多加入2个字段来便于查找

节点路径字段,节点深度字段

比如你的编号3数据

3 1 0,1,3 2

其中0,1,3表示从根到自己的节点路径,最后2表示节点深度为2

这样查找起来比较方便点
ycproc 2011-06-13
  • 打赏
  • 举报
回复
循环递归
子夜__ 2011-06-13
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 qiudong_5210 的回复:]

引用 5 楼 wxr0323 的回复:

...

类似这种

实现


实现tree的做出来了,现在想根据一个Id找到根父级的Id,不知道该怎么写了
[/Quote]
方法很多

你可以用一个哈希表来存

Hashtable ht = new Hashtable();
//ht.Add("子节点ID","父节点ID");
ht.Add(1,0);
ht.Add(2,1);
ht.Add(3,1);
ht.Add(4,1);
Response.Write(ht[2].ToString());
//显示的就是ID为2的父节点ID 为1
//表结构就按照那个弄吧
Levin 2011-06-13
  • 打赏
  • 举报
回复
递归查找。
qiudong_5210 2011-06-13
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 wxr0323 的回复:]

...

类似这种

实现
[/Quote]

实现tree的做出来了,现在想根据一个Id找到根父级的Id,不知道该怎么写了
子夜__ 2011-06-13
  • 打赏
  • 举报
回复
qiudong_5210 2011-06-13
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 maysaber 的回复:]

类似tree的遍历,找到LID不是为0为止?
[/Quote]

找到LId为0的为止
qiudong_5210 2011-06-13
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 wxr0323 的回复:]

输入4,返回1,输入3,返回1 输入6,返回5,输入5,返回5

没看懂你的数据是怎么回事的。

1 0
2 1
3 1
4 1
5 0
6 5

改成这种的?
[/Quote]
如果把LId改成ParentId是否更好理解一点呢
4的父级是3,3的父级是2,2的父级是1, 4的根父级就是1,1没有父级,就是根父级
maysaber 2011-06-13
  • 打赏
  • 举报
回复
类似tree的遍历,找到LID不是为0为止?
maysaber 2011-06-13
  • 打赏
  • 举报
回复
mark 顶
子夜__ 2011-06-13
  • 打赏
  • 举报
回复
输入4,返回1,输入3,返回1 输入6,返回5,输入5,返回5

没看懂你的数据是怎么回事的。

1 0
2 1
3 1
4 1
5 0
6 5

改成这种的?

62,041

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧