如何在分层(连接)oracle查询中省略较少的父节点?

时间:2013-08-08 15:11:26

标签: sql oracle

给定一个名为CATEGORY的表,其中包含列

  • CATEGORY_NAME
  • CATEGORY_PARENT_NAME
  • ACTIVE

这个查询

SELECT *
FROM CATEGORY
WHERE ACTIVE = 'TRUE'
START WITH CATEGORY_PARENT_NAME IS NULL   
CONNECT BY CATEGORY_PARENT_NAME = PRIOR CATEGORY_NAME   
ORDER SIBLINGS BY MENU_INDEX

我正在尝试仅获取其根父级处于活动状态的活动子节点,但oracle也会返回非活动根的活动子节点,即使通过其父节点在where子句中进行了过滤也是如此。我做错了什么?

2 个答案:

答案 0 :(得分:2)

您应该修改START BY子句以包含ACTIVE = TRUE,以便只考虑那些处于活动状态的根。

稍后将应用WHERE子句,以便您只能过滤掉ACTIVE子节点。

 select *
   from category
  where active = 'TRUE'
  start with category_parent_name is null
    and active = 'TRUE' 
connect by category_parent_name = prior category_name   
  order siblings by menu_index;

答案 1 :(得分:0)

以下查询(请参阅SQL Fiddle)将为您提供 root 处于活动状态的所有活动节点:

SELECT *
FROM (
  SELECT c.*,
    PRIOR c.ACTIVE AS PARENT_ACTIVE,
    CONNECT_BY_ROOT(c.CATEGORY_NAME) AS CATEGORY_ROOT_NAME,
    CONNECT_BY_ROOT(c.ACTIVE) AS ROOT_ACTIVE
  FROM CATEGORY c
  WHERE c.ACTIVE = 'TRUE'
  START WITH c.CATEGORY_PARENT_NAME IS NULL   
  CONNECT BY c.CATEGORY_PARENT_NAME = PRIOR c.CATEGORY_NAME   
  ORDER SIBLINGS BY c.MENU_INDEX
) a
WHERE a.ROOT_ACTIVE = 'TRUE'

要进一步过滤结果,只包括其父级,祖父级和层次结构根目录下的所有祖先节点都处于活动状态的活动节点(请参阅SQL Fiddle):

SELECT *
FROM (
  SELECT c.*,
    PRIOR c.ACTIVE AS PARENT_ACTIVE,
    CONNECT_BY_ROOT(c.CATEGORY_NAME) AS CATEGORY_ROOT_NAME,
    CONNECT_BY_ROOT(c.ACTIVE) AS ROOT_ACTIVE,
    SYS_CONNECT_BY_PATH(c.ACTIVE, '/') AS ACTIVE_PATH
  FROM CATEGORY c
  WHERE c.ACTIVE = 'TRUE'
  START WITH c.CATEGORY_PARENT_NAME IS NULL   
  CONNECT BY c.CATEGORY_PARENT_NAME = PRIOR c.CATEGORY_NAME   
  ORDER SIBLINGS BY c.MENU_INDEX
) a
WHERE a.ROOT_ACTIVE = 'TRUE'
  AND a.ACTIVE_PATH NOT LIKE '%FALSE%'

<强>提示

  • 使用CONNECT_BY_ROOT运算符从根节点获取列值。
  • 使用PRIOR运算符从父节点获取列值(当您在根节点时​​只需注意NULL
  • 使用SYS_CONNECT_BY_PATH函数获取一直到根节点的列值。