表数据类似于树机构,有许多的层次,输入某一个id,需要查询出该id下的所有子节点和树枝节点的id(包含该节点下的树枝节点和子节点下的树枝节点,以此类推)。简化表大致如下
id pid
1
2 1
3 1
4 2
5 3
6 4
7 4
8 4例如,我输入1,查询出的结果是:2,3,4,5,6,7,8
如果输入的是3,结果则是5.使用存储过程和递归查询是可以查询出来的。各位看看 这个需求能否使用一个sql写出来?
id pid
1
2 1
3 1
4 2
5 3
6 4
7 4
8 4例如,我输入1,查询出的结果是:2,3,4,5,6,7,8
如果输入的是3,结果则是5.使用存储过程和递归查询是可以查询出来的。各位看看 这个需求能否使用一个sql写出来?
解决方案 »
- 求一条比较复杂的sql语句!
- Oracle 9.2.0.8 SGA配置问题!!急急急
- 一个奇怪的错误,高分跪求答案
- 存储过程执行后不出错,但表中也未插入数据,是何原因?
- 求SQL 找出时间最小的一行
- 使用exp备份文件时,用当前日期做为文件名遇到问题
- 在pb中运行execute immediate :ls_str;出错
- 直接用SQL可以从SYS.ALL_TAB_COLS表中可以查到结果,可是从存储过程中确拿不到?
- 这么简单的sql怎么效率不高呢?
- oracle中between..and..的非常容易错误的使用点:字符串,数字的区间比较
- 性格测试 系统数据库设计
- 求sql语句,求id为偶数的数据。
star with A.id = ?
connect by prior A.id = A.parent_id
SQL> with t as (
2 select 1 id, null pid from dual union all
3 select 2 id, 1 pid from dual union all
4 select 3 id, 1 pid from dual union all
5 select 4 id, 2 pid from dual union all
6 select 5 id, 3 pid from dual union all
7 select 6 id, 4 pid from dual union all
8 select 7 id, 4 pid from dual union all
9 select 8 id, 4 pid from dual)
10 SELECT id, pid FROM t START WITH pid = 1 CONNECT BY PRIOR id = pid;
ID PID
---------- ----------
2 1
4 2
6 4
7 4
8 4
3 1
5 3
7 rows selected
SQL>
SQL> --指定start with pid的值就行了,start with pid=3
SQL> with t as (
2 select 1 id, null pid from dual union all
3 select 2 id, 1 pid from dual union all
4 select 3 id, 1 pid from dual union all
5 select 4 id, 2 pid from dual union all
6 select 5 id, 3 pid from dual union all
7 select 6 id, 4 pid from dual union all
8 select 7 id, 4 pid from dual union all
9 select 8 id, 4 pid from dual)
10 SELECT id, pid FROM t START WITH pid = 3 CONNECT BY PRIOR id = pid;
ID PID
---------- ----------
5 3
SQL>
最后是在java代码里是使用递归来实现这个功能。。
性能差了点。。