您的位置:程序门 -> ms-sql server -> 基础类



求sql查询语句


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


求sql查询语句
发表于:2007-07-16 15:58:57 楼主
数据库表
id           sb_1           sb_2
5               23               24
6               23               25
7               24               32
8               32               26
9               26               33

把相关的数据按一个记录查出来
发表于:2007-07-16 16:00:111楼 得分:0
什么叫 "相关的数 "
发表于:2007-07-17 08:15:372楼 得分:0
比如我查32就是把他的上下关联的查出来
23   24   32   26   33
要查23那就是
23   24   32   26   33
23   25
发表于:2007-07-17 09:26:033楼 得分:0
“相关”的关系还是没说清,是不是查32时找到id=7的记录,再根据id=7的记录中的sb_1=24再找sb_2=24的记录id=5,这样一连串地找下去?如果是,按这种“相关”性,为什么没有25(id=6)呢?
发表于:2007-07-17 09:48:184楼 得分:0
create   table   tb

id   int   identity(5,1),
sb_1   int,
sb_2   int
)
insert   into   tb  
select   23,24   union   all
select   23,25   union   all
select   24,32   union   all
select   32,26   union   all
select   26,33
go

--查找所有父结点及子节点的问题,当前假设sb_1为父结点,sb_2为子结点建立函数,查找所有子结点
create   function   f_pid(@sb_1   int)
returns   @t_level   table(sb_1   int,level   int)
as
begin
declare   @level   int
set   @level=1
insert   @t_level   select   @sb_1,@level
while   @@rowcount> 0
begin
set   @level=@level+1
insert   @t_level   select   a.sb_2,@level
from   tb   a,@t_level   b
where   a.sb_1=b.sb_1
and   b.level=@level-1
end
return
end
go

select   *   from   dbo.f_pid(23)

sb_1                 level
-----------   -----------
23                     1
24                     2
25                     2
32                     3
26                     4
33                     5

(6   行受影响)
如要查子结点,在函数中做相应操作即可
发表于:2007-07-17 10:17:105楼 得分:0
学习中~


快速检索

最新资讯
热门点击