求一SQL语句,或SQL函数

unwonted 2005-10-31 02:27:43
现要进行一个查询,有两个字段,为'本层'(id),'上一层'(pid);
怎样知道一个id,把录属于id 的所有上级的层都查询出来??
...全文
65 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
unwonted 2005-10-31
  • 打赏
  • 举报
回复
我已解决这问题了,谢谢你的提示,查询方法为:
select distinct a.id from tb a left join tb b on a.pid=b.id where a.pid=@***
union
select distinct a.id from tb a left join tb b on a.pid=b.id where b.pid=@***
samfeng_2003 2005-10-31
  • 打赏
  • 举报
回复
给你列个例子吧!

[create] table t(id int,name char(1),parent_id int,sfmx int)
insert into t select 1,'a',0,0
insert into t select 2,'b',1,0
insert into t select 3,'c',1,0
insert into t select 4,'d',1,1
insert into t select 5,'e',2,1
insert into t select 6,'f',3,1
go

select a.id,isnull(c.name+'-','')+isnull(b.name+'-','')+isnull(a.name,'')
from t a
left join t b on a.parent_id=b.id
left join t c on b.parent_id=c.id




drop table t
unwonted 2005-10-31
  • 打赏
  • 举报
回复
更正,应该是知道一id,查询录属于它的所有下级层(包括录属于它下级的下级的所有层)

34,587

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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