日期:2014-05-18  浏览次数:20548 次

求写一条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;
go
create table tb(nodeid int, parentid int, nodename varchar(32))
go
insert 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';
go

declare @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 = @i
union all
select * from T1
union all
select nodeid, parentid, nodename from T2 where rn = 1

/*
(14 行受影响)
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

(7 行受影响)
*/