希望找到比循环搜索sql表(oracle)更好的解决方案

希望找到比循环搜索sql表(oracle)更好的解决方案,sql,oracle,loops,datatable,solution,Sql,Oracle,Loops,Datatable,Solution,我有一张桌子如下 我只知道第一个from_字段的值,并且需要推断最后一个to_字段是哪一行。 例如,已知起点是from_字段中的1a,因此下一个起点是to_字段中的2a,然后从from_字段中的2a到to_字段中的3a,路径如下: 1a->2a->3a->4a->5a 当type字段的值为end时,表示该行是最后一行 从_场 托福场 类型 1a 2a 路径 2a 3a 路径 3a 4a 路径 4a 5a 结束 1b 2b 路径 2b 3b 结束 1c 2c 结束 看起来像是分层查询。第1-10行

我有一张桌子如下

我只知道第一个from_字段的值,并且需要推断最后一个to_字段是哪一行。 例如,已知起点是from_字段中的1a,因此下一个起点是to_字段中的2a,然后从from_字段中的2a到to_字段中的3a,路径如下:

1a->2a->3a->4a->5a

当type字段的值为end时,表示该行是最后一行

从_场 托福场 类型 1a 2a 路径 2a 3a 路径 3a 4a 路径 4a 5a 结束 1b 2b 路径 2b 3b 结束 1c 2c 结束
看起来像是分层查询。第1-10行中的样本数据;查询从第11行开始

SQL> with test (from_field, to_field) as
  2    (select '1a', '2a' from dual union all
  3     select '2a', '3a' from dual union all
  4     select '3a', '4a' from dual union all
  5     select '4a', '5a' from dual union all
  6     --
  7     select '1b', '2b' from dual union all
  8     select '2b', '3b' from dual union all
  9     select '1c', '2c' from dual
 10    )
 11  select from_field,
 12         the_last_to_field
 13  from (select connect_by_root from_field   as from_field,
 14               from_field                   as the_last_to_field,
 15               connect_by_isleaf            as leaf
 16        from test
 17        connect by from_field = prior to_field
 18        start with from_field = '&par_from_field'
 19       )
 20  where leaf = 1;
Enter value for par_from_field: 1a

FROM_FIELD      THE_LAST_TO_FIELD
--------------- -----------------
1a              4a

SQL> /
Enter value for par_from_field: 3a

FROM_FIELD      THE_LAST_TO_FIELD
--------------- -----------------
3a              4a

SQL> /
Enter value for par_from_field: 1b

FROM_FIELD      THE_LAST_TO_FIELD
--------------- -----------------
1b              2b

SQL> /
Enter value for par_from_field: 1c

FROM_FIELD      THE_LAST_TO_FIELD
--------------- -----------------
1c              1c

SQL>