一个部门的表,结构如下:
dept_id     belong_to
   1          NULL
   2          NULL
   3            1
   4            1
   5            2
......其中,dept_id是部门的ID,belong_to 是该部门是属于哪个部门管辖。例如:dept_id = 3, belong_to = 1 表示,部门 3 属性于部门 1 管辖。如何使用 SQL 语句才能产生下面的结构:
1
3
4
2
5
即将某个部门的所有下属部门列在它的下面。

解决方案 »

  1.   

    select dept_id
    from table 
    start with dept_id=1
    connect by belong_to = prior dept_id
      

  2.   

    start with dept_id=1 
    这样做不行,要是 dept_id 不是从1开头的就无法执行了。我的表中, dept_id 是vchar 类型,该如何是好呢?
      

  3.   

    start with dept_id= 1  
    不一定非要是1  阿
    你可以制定部门 id 的阿 比如说start with dept_id= 2
    结果是
    2
    5
      

  4.   

    如果你的 dept_id  虽然是vchar  但是都是数字的话,  
    oracle 会自动帮你转换的。
      

  5.   

    理解错了你的意思 sorry  
      

  6.   

    嗯,我知道怎么写这个SQL语句了,谢谢!
      

  7.   


    create table  DEP(dept_id varchar(10),belong_to varchar(10))
    insert into DEP(dept_id) values('1')
    insert into DEP(dept_id) values('2')
    insert into DEP(dept_id,belong_to) values('3','1')
    insert into DEP(dept_id,belong_to) values('4','1')
    insert into DEP(dept_id,belong_to) values('5','2')
    select * from DEPselect  dept_id
    from DEP
    start with belong_to is  null
    connect by  belong_to = prior dept_id DEPT_ID    
     ---------- 
     1          
     3          
     4          
     2          
     5           5 record(s) selected [Fetch MetaData: 0/ms] [Fetch Data: 0/ms] 
      

  8.   

    SELECT DEPT_ID FROM TAB 
    START WITH BELONG_TO IS NULL
    CONNECT BY PRIOR DEPT_ID=BELONG_TO