SQL:SEARCH DEPTH FIRST和 SEARCH BREADTH FIRST

用SQL实现深度优先搜索和广度优先搜索

语法举列子:

WITH T AS (
SELECT 'B' A , 'A' B , 2 N FROM DUAL UNION ALL
SELECT 'C' A , 'A' B , 4 N FROM DUAL UNION ALL
SELECT 'D' A , 'B' B , 3 N FROM DUAL UNION ALL
SELECT 'E' A , 'B' B , 3 N FROM DUAL UNION ALL
SELECT 'F' A , 'B' B , 2 N FROM DUAL UNION ALL
SELECT 'G' A , 'C' B , 4 N FROM DUAL UNION ALL
SELECT 'H' A , 'C' B , 2 N FROM DUAL UNION ALL
SELECT 'I' A , 'H' B , 5 N FROM DUAL
)
, T1 (A,B,N,L) AS (                   -------------------------指明列的信息,不然会报错 ORA-32488: WITH clause element did not have a column alias list
SELECT T.A,T.B,T.N,1 FROM T
WHERE T.B = 'A'
UNION ALL
SELECT T.A, T.B, T1.N*T.N ,L+1  --------------------------------相当于迭代
FROM T , T1
WHERE T1.A = T.B
)

SEARCH DEPTH FIRST BY B SET SEQ  -----------------------类似rownum
SELECT
 *
FROM  (SELECT A,B,N,SEQ
       FROM   T1 )

结果:

A开始,然后B,到C,再回溯子树A,C,H

SQL> 
 24  /
 
A B          N        SEQ          L
- - ---------- ---------- ----------
B A          2          1          1
D B          6          2          2
E B          6          3          2
F B          4          4          2
C A          4          5          1
G C         16          6          2
H C          8          7          2
I H         40          8          3
 
8 rows selected

对比广度:

先遍历完所有A,所有B,所有C

SQL> 
 24  /
 
A B          N        SEQ          L
- - ---------- ---------- ----------
B A          2          1          1
C A          4          2          1
F B          4          3          2
E B          6          4          2
D B          6          5          2
H C          8          6          2
G C         16          7          2
I H         40          8          3
 
8 rows selected
 


你可能感兴趣的:(SQL:SEARCH DEPTH FIRST和 SEARCH BREADTH FIRST)