表数据类似于树机构,有许多的层次,输入某一个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写出来?

解决方案 »

  1.   

    select * from A
    star with  A.id = ?
    connect by prior A.id = A.parent_id
      

  2.   

    SQL> --指定start with pid的值就行了,start with pid=1
    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> 
      

  3.   

    谢谢楼上我使用的数据库是mysql,请问这个sql该如何写呢?上面的sql在mysql无法执行。
      

  4.   

    CONNECT BY在oracle中是可以查询出某节点下的所有子节点,但在MySQL中好像还没有,只见过用存储过程或递归来实现的,还未见到直接用sql语句查的,等待高手解答
      

  5.   

    mysql的来oracle问语句会不会悲剧了点
      

  6.   

    更悲剧的是发现mysql没有类似CONNECT BY的语法,
    最后是在java代码里是使用递归来实现这个功能。。
    性能差了点。。