0

我有分层结构的表(n,n_parent,data):

例如:

  • 目录 1 (1,0,null)
    • 子目录 1 (44,1,null)
      • 项目 1 (83,44,a)
      • 项目 2 (98,44,b)
    • 子目录 2 (46,1,null)
      • 第 1 项 (8,46,c)
      • 项目 2 (9,46,d)
  • 目录 2 (4,0,null)
    • 子目录 1 (54,4,null)
      • 项目 1 (43,54,e)
      • 项目 2 (48,54,f)
    • 子目录 2 (101,4,null)
      • 项目 1 (19,101,g)
      • 项目 2 (314,101,h)

如果我有 id,我用这个 id 构建项目并且它是父母:例如我有 id:83、98、48、9:

SELECT distinct name, n, n_parent FROM portalmdo.zre_filter a START WITH N in (83, 98, 48, 9) CONNECT BY PRIOR N_PARENT = N

Directory 1 (1,0,null)    
Subdirectory 1 (44,1,null)  
Item 1 (83,44,a)  
Item 2 (98,44,b)    
Subdirectory 2 (46,1,null)    
Item 2 (9,46,d)    
Directory 2 (4,0,null)    
Subdirectory 1 (54,4,null)    
Item 2 (48,54,f)

(顺序不是重要问题)

我希望将现场数据传输给父母:例如:

Directory 1 (1,0,a)    
Subdirectory 1 (44,1,a)  
Item 1 (83,44,a)  
Directory 1 (1,0,b)    
Subdirectory 1 (44,1,b) 
Item 2 (98,44,b)    
Directory 1 (1,0,d)  
Subdirectory 2 (46,1,d)    
Item 2 (9,46,d)    
Directory 2 (4,0,f)    
Subdirectory 1 (54,4,f)    
Item 2 (48,54,f)
4

1 回答 1

1

您可以使用CONNECT_BY_ROOT (10g+):

SQL> WITH data AS (
  2     SELECT 'Directory 1' name, 1 n,0 n_p,null dat FROM DUAL
  3     UNION ALL SELECT 'Subdirectory 1', 44,1,null FROM DUAL
  4     UNION ALL SELECT 'Item 1', 83,44,'a' FROM DUAL
  5     UNION ALL SELECT 'Item 2', 98,44,'b' FROM DUAL
  6     UNION ALL SELECT 'Subdirectory 2', 46,1,null FROM DUAL
  7     UNION ALL SELECT 'Item 1', 8,46,'c' FROM DUAL
  8     UNION ALL SELECT 'Item 2', 9,46,'d' FROM DUAL
  9     UNION ALL SELECT 'Directory 2', 4,0,null FROM DUAL
 10     UNION ALL SELECT 'Subdirectory 1', 54,4,null FROM DUAL
 11     UNION ALL SELECT 'Item 1', 43,54,'e' FROM DUAL
 12     UNION ALL SELECT 'Item 2', 48,54,'f' FROM DUAL
 13     UNION ALL SELECT 'Subdirectory 2', 101,4,null FROM DUAL
 14     UNION ALL SELECT 'Item 1', 19,101,'g' FROM DUAL
 15     UNION ALL SELECT 'Item 2', 314,101,'h' FROM DUAL
 16  )
 17  SELECT DISTINCT name, n, n_p, connect_by_root(dat) dat
 18    FROM data a
 19  START WITH N IN (83, 98, 48, 9)
 20  CONNECT BY PRIOR N_P = N;

NAME                    N    N_P DAT
---------------------- -- ------ -------
Item 2                 48     54 f
Item 1                 83     44 a
Item 2                 98     44 b
Subdirectory 1         44      1 b
Subdirectory 1         44      1 a
Item 2                  9     46 d
Directory 1             1      0 b
Subdirectory 2         46      1 d
Directory 1             1      0 d
Directory 2             4      0 f
Subdirectory 1         54      4 f
Directory 1             1      0 a
于 2012-09-20T10:15:50.577 回答