目前有个表:层次ID,层次name,排序号,父id
层次id4位编码:比如0001  下一级就是00010001
排序号为1、2,不同级别之间排序号可以重复。
如何能够按照层次关系查出数据,并且按照排序号排序。

解决方案 »

  1.   

    建表语句:create table T  (
       CCID             CHAR(12)                        not null,
       CCNAME             VARCHAR2(100)                   not null,
       PXH               INTEGER 
       constraint PK_T primary key (CCID)
    );
    insert into t values('0001',        '家用电器',  1  );
    insert into t values('00010001',    '小家电',    2  );
    insert into t values('00010002',    '大家电',    1  );
    insert into t values('000100020001','洗衣机',    35 );
    insert into t values('000100020002','平板电视',  30 );
    insert into t values('000100020003','冰箱',      33 );
    insert into t values('0002',        '手机数码',  2  );
    insert into t values('00020001',   '手机通讯',   3  );
    insert into t values('00020002',    '手机配件',  2  );
    insert into t values('00020003',    '数码配件',  5  );
    insert into t values('0003',        '服饰鞋帽',  1  );
    insert into t values('0004',        '图书影视',  5  );
      

  2.   


     select  *  from t order by  ccid, pxh排序是乱的。
    有没有好的sql语句可以实现
      

  3.   

    和同事讨论后得出结论:
    不用排序号:select * from t start with ccid='0001' connect by prior ccid=trunc(ccid/10000) order by ccid
    用排序号目前还没想出来。
      

  4.   

    搞定了 不知道你用不用父id
    用父id就这么写:
    select * from t start with ccid='0001' connect by prior ccid=父id order siblings by ccid;
    不用就这么写:
    select * from t start with ccid='0001' connect by prior ccid=trunc(ccid/10000) order siblings by ccid;
      

  5.   

    phx是当前记录所在逻辑层级么?
      

  6.   

    pamod,我测试了一下你的sql,对于0002 0003这2条数据没有查出来,
    另外没有实现按照排序号排序
      

  7.   

    呵呵 不好意思
    这里
    第2个sql写错了 应该是
    select * from t start with ccid='0001' connect by prior ccid=trunc(ccid/10000) order siblings by pxh;
      

  8.   

    第一个sql的ooder by 也是 order siblings by pxh;
      

  9.   

    不能连续回复超过4次,,csdn
      

  10.   

    原因明白了:
    你第一个问题的原因是由于0002,0003和0001不是一颗树。
    这个sql查询出来的是1个树的完整结构第二个原因就是我那个sql  order by 写错了
      

  11.   

    select * from t1 start with ccid in (select ccid from t1 where length(ccid)=4) connect by prior ccid=trunc(ccid/10000) order siblings by pxh,ccid;
    搞定
      

  12.   

    同事温馨提示 in 效率比较差,你可以试试exists
      

  13.   

    谢谢pamod。
    实验了一下,完全正确。
    另外我还想接着问一个问题,如果除了上面的要求,
    再加上同时查出是否是叶节点,也就是说排序的同时,查出来来这个层次是否还有子节点,没有就是0,有就是1.
      

  14.   

    select ccid,CONNECT_BY_ISLEAF "ISLEAF" from t1 start with ccid in (select ccid from t1 where length(ccid)=4) connect by  prior ccid=trunc(ccid/10000) order siblings by pxh,ccid;
    0是有;1是没有
      

  15.   

    oracle的递归查询有伪列level表示树结构的层次
    你可以按照level排序