在CONNECT BY PRIOR提取信息

时间:2012-09-20 10:01:04

标签: sql plsql

我有分层结构的表(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,44,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)

1 个答案:

答案 0 :(得分: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