有一张表LINE,结构如下:
LINE_ID POINT1_ID  POINT2_ID
   1        0          1
   2        1          2
   4        2          3
该表存储了一系列的线段的两个端点的ID,表中各线段首尾相连会组成一条长的线段(可能会有环路),以测试数据为例,line1、line2、line3、line4、line5组成了一条完整的线段链。
现在知道完整线段链的起至点ID,需要用一条SQL语句查询出整个线段链各点的列表(以连接顺序排序),如:
index    point_id
  1          0
  2          1
  3          2
  4          3该问题难点有两个
1> 线段是没有方向的,即实际存储数据可能是这样
LINE_ID POINT1_ID  POINT2_ID
   1        0          1
   2        2          1
   3        2          32> 可能存在环路,即可能有这样的数据
LINE_ID POINT1_ID  POINT2_ID
   1        0          1
   2        1          2
   3        1          3
   4        2          4
   5        3          4我用的数据库是Oracle10g,需要用一条SQL得到结果,不希望使用存储过程或函数。

解决方案 »

  1.   

    如果没有环路的话,可以直接使用connect by 按树查询。
    select index from tablename
    connect by prior point1_id = point2_id 
    start with index = 起点INDEX。
    可是如果存在环路就不行了。
      

  2.   

    如果有环路,试试用nocycle看看:with linklist as (
    select 1 lineid, 0 point1, 1 point2 from dual
    union all select 2,1,2 from dual
    union all select 3,1,3 from dual
    union all select 4,2,4 from dual
    union all select 5,3,4 from dual
    union all select 6,4,1 from dual )select lineid from linklist
    start with lineid=1
    connect by nocycle point1 = prior point2;
      

  3.   

    线段没有方向的问题可以解决, 但是环路就不知道怎么办了.select
    from
    (select line_id, 
    case when point1_id>point2_id then point2_id else point1_id end as point1_id, 
    case when point1_id>point2_id then point1_id else point2_id end as point2_id
    from line)
    start with point1_id=0
    connect by prior point1_id=point2_id
    /
      

  4.   

    sorry, 上面少写了一个 select *