【问题标题】:Want to find a better solution than loop searching sql table(oracle)想找到比循环搜索sql table(oracle)更好的解决方案
【发布时间】:2021-07-13 08:57:43
【问题描述】:

我有一张如下表。

我只知道第一个from_field的值,需要推断最后一个to_field是哪一行。 比如已知起点是from_field字段中的1a,那么接下来就是to_field字段中的2a,然后从from_field字段中的2a到to_field字段中的3a,路径如下:

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

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

from_field to_field type
1a 2a path
2a 3a path
3a 4a path
4a 5a end
1b 2b path
2b 3b end
1c 2c end

这个表有数万行。我目前使用循环重复搜索行以找到最后一个to_field,但这需要很多时间。 谁有更好的解决方案?

【问题讨论】:

    标签: sql oracle loops datatable solution


    【解决方案1】:

    看起来像一个分层查询。第 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>
    

    【讨论】:

      猜你喜欢
      • 2014-06-22
      • 1970-01-01
      • 2014-07-20
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多