ID, fatherid
1 0
2 1
3 1
4 2
5 2
. .
. .
现在的问题是想通过SQL查出所有fatherid相同的值和他们的后代,也就是说,如果现在查询条件是1的话,因为1是所有行的父类,那就需要列出所有的值,如果查询条件是2的话,就需要列出4,5行,以及所有根节点是2的行。通俗点说,这个表就是个树,现在需要根据给出的一个节点,列出所有的子节点,请问这样的SQL该怎么写呢?谢谢大家了
7 个解决方案
#1
connect by
#2
with temp as
(
select 1 a, 0 b from dual
union all
select 2, 1 from dual
union all
select 3, 1 from dual
union all
select 4, 2 from dual
union all
select 5, 2 from dual
)
select * from temp start with b=0 connect by prior a=b
order by a
--result:
--b=0
1 0
2 1
3 1
4 2
5 2
--b=1
2 1
3 1
4 2
5 2
--b=2
4 2
5 2
5 2
#3
to cosio:
能解释下
with temp as
(
select 1 a, 0 b from dual
union all
select 2, 1 from dual
union all
select 3, 1 from dual
union all
select 4, 2 from dual
union all
select 5, 2 from dual
)
这个表是什么意思么,尤其是那个a,b,好像么见过这种形式的东东。么见笑,见的东西比较少。。。。
能解释下
with temp as
(
select 1 a, 0 b from dual
union all
select 2, 1 from dual
union all
select 3, 1 from dual
union all
select 4, 2 from dual
union all
select 5, 2 from dual
)
这个表是什么意思么,尤其是那个a,b,好像么见过这种形式的东东。么见笑,见的东西比较少。。。。
#4
楼主看下层次化查询(树形查询)
select * from tt
where level>1
start with id=2
connect by prior fatherid=id
start with那里的条件可改为你要查的父节点
select * from tt
where level>1
start with id=2
connect by prior fatherid=id
start with那里的条件可改为你要查的父节点
#5
select * from temp start with b=0 connect by prior a=b
order by a
上面的代码我只需要把a,b改成我自己的列名就可以了,是吧?
#6
to wildwave以及cosio,我自己测试了,问题已经解决了,谢谢你们。
#7
上面的列名是叫列的别名!
改为你自己的列名就可以了,
我是看数据简单,不用建名,直接用
with temp as 的写法!
改为你自己的列名就可以了,
我是看数据简单,不用建名,直接用
with temp as 的写法!
#1
connect by
#2
with temp as
(
select 1 a, 0 b from dual
union all
select 2, 1 from dual
union all
select 3, 1 from dual
union all
select 4, 2 from dual
union all
select 5, 2 from dual
)
select * from temp start with b=0 connect by prior a=b
order by a
--result:
--b=0
1 0
2 1
3 1
4 2
5 2
--b=1
2 1
3 1
4 2
5 2
--b=2
4 2
5 2
5 2
#3
to cosio:
能解释下
with temp as
(
select 1 a, 0 b from dual
union all
select 2, 1 from dual
union all
select 3, 1 from dual
union all
select 4, 2 from dual
union all
select 5, 2 from dual
)
这个表是什么意思么,尤其是那个a,b,好像么见过这种形式的东东。么见笑,见的东西比较少。。。。
能解释下
with temp as
(
select 1 a, 0 b from dual
union all
select 2, 1 from dual
union all
select 3, 1 from dual
union all
select 4, 2 from dual
union all
select 5, 2 from dual
)
这个表是什么意思么,尤其是那个a,b,好像么见过这种形式的东东。么见笑,见的东西比较少。。。。
#4
楼主看下层次化查询(树形查询)
select * from tt
where level>1
start with id=2
connect by prior fatherid=id
start with那里的条件可改为你要查的父节点
select * from tt
where level>1
start with id=2
connect by prior fatherid=id
start with那里的条件可改为你要查的父节点
#5
select * from temp start with b=0 connect by prior a=b
order by a
上面的代码我只需要把a,b改成我自己的列名就可以了,是吧?
#6
to wildwave以及cosio,我自己测试了,问题已经解决了,谢谢你们。
#7
上面的列名是叫列的别名!
改为你自己的列名就可以了,
我是看数据简单,不用建名,直接用
with temp as 的写法!
改为你自己的列名就可以了,
我是看数据简单,不用建名,直接用
with temp as 的写法!