首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求写一条sql语句,搞了一下午没搞出来,是mysql的解决方案

2012-06-09 
求写一条sql语句,搞了一下午没搞出来,是mysql的比如表结构是这样的:节点id父节点id节点名nodeidparentidno

求写一条sql语句,搞了一下午没搞出来,是mysql的
比如表结构是这样的:

节点id 父节点id 节点名
nodeid parentid nodename
  1 -1 根
  2 1 A
  3 1 B
  4 1 C
  5 2 A-1
  6 2 A-2
  7 2 A-3
  8 3 B-1
  9 3 B-2
  10 4 C-1
  11 5 A-1-1
  12 5 A-1-2
  13 8 B-1-1
  14 8 B-1-2
  .................
  一个树形,无限级的,
我要的结果就是一次查两级的,比如:
我传入一个nodeid是1的节点号,要的结果是查出g该节点,并且属于该节点号的所有子节点,并且如果子节点还有子节点的话只要子节点下的子节点的一条数据就够,不要都出来;

比如我传入一个1,出来的结果应该是:
nodeid parentid nodename
  1 -1 根
  2 1 A
  3 1 B
  4 1 C
  5 2 A-1
  8 3 B-1
  10 4 C-1

如果我传入一个2的话,结果应该是:
nodeid parentid nodename
  2 1 A
  5 2 A-1
  6 2 A-2
  7 2 A-3
  11 5 A-1-1

就是这样,求大牛门帮忙啊。。。。

[解决办法]
树形数据的查找 mysql的话楼主发错地方了
[解决办法]

[解决办法]

SQL code
if OBJECT_ID('tb') is not null Drop table tb;gocreate table tb(nodeid int, parentid int, nodename varchar(32))goinsert into tb(nodeid, parentid, nodename)select 1, -1, '根' union all select 2, 1, 'A' union all select 3, 1, 'B' union all select 4, 1, 'C' union all select 5, 2, 'A-1' union all select 6, 2, 'A-2' union all select 7, 2, 'A-3' union all select 8, 3, 'B-1' union all select 9, 3, 'B-2' union all select 10, 4, 'C-1' union all select 11, 5, 'A-1-1' union all select 12, 5, 'A-1-2' union all select 13, 8, 'B-1-1' union all select 14, 8, 'B-1-2';godeclare @i int;set @i = 1;     --传入的节点号with T1 as(    select * from tb where tb.parentid = @i),T2(rn, nodeid, parentid, nodename) as(    select rn = row_number() over(partition by tb.parentid order by tb.nodeid)        ,tb.* from tb        join T1        on tb.parentid = T1.nodeid)select * from tb where nodeid = @iunion allselect * from T1union allselect nodeid, parentid, nodename from T2 where rn = 1/*(14 行受影响)nodeid      parentid    nodename----------- ----------- --------------------------------1           -1          根2           1           A3           1           B4           1           C5           2           A-18           3           B-110          4           C-1(7 行受影响)*/ 

热点排行