Oracle SQL:如何进行层次结构,并为每个“叶子”执行选择到另一个表

时间:2012-03-22 10:24:30

标签: oracle hierarchy

我有两个相关实体“ESTABELECIMENTO”和“LOCAL_PRESCRICAO”,对于“ESTABELECIMENTO”层次结构的每个节点,我想列出“LOCAL_PRESCRICAO”中的“子”......

enter image description here

你看......我可以通过这种方式将层次结构设为“ESTABELECIMENTO”

select lpad(' ',2*(level-1)) 
      || estabelecimento.id 
      || ' ' || estabelecimento.nomecompleto
from estabelecimento
where estabelecimento.activo = 1
start with estabelecimento.id = 36
connect by prior estabelecimento.id = estabelecimento.estabelecimetnopaiid

但是现在我想列出与“ESTABELECIMENTO”相关联的每个“LOCAL_PRESCRICAO”并维护层次结构......我怎样才能实现这一目标?

2 个答案:

答案 0 :(得分:1)

这应该按照您的要求进行。

WITH e
  AS (SELECT    LPAD (' ', 2 * (LEVEL - 1))
             || estabelecimento.id
             || ' '
             || estabelecimento.nomecompleto
        FROM estabelecimento
       WHERE estabelecimento.activo = 1
       START WITH estabelecimento.id = 36
     CONNECT BY PRIOR estabelecimento.id = estabelecimento.estabelecimetnopaiid)
SELECT e.*,
       lp.*
  FROM e
 INNER JOIN ESTABELECIMENTO_LOCAL_PRESCRICAO elp
    ON (e.id = elp.estabelecimentoid)
 INNER JOIN LOCAL_PRESCRICAO lp
    ON (lp.id = elp.localprescricaoid);

它会返回您在分层查询中选择的所有行以及LOCAL_PRESCRICAO表中的相应行。

希望它有所帮助...

编辑:

道歉,我忽略了ID与其他领域的连接。 这应该可以解决问题。

WITH e
  AS (SELECT rownum AS rnum, e_data, id
        FROM (SELECT    LPAD (' ', 2 * (LEVEL - 1))
                     || estabelecimento.id
                     || ' '
                     || estabelecimento.nomecompleto AS e_data,
                     estabelecimento.id AS id
                FROM estabelecimento
               WHERE estabelecimento.activo = 1
               START WITH estabelecimento.id = 36
             CONNECT BY PRIOR estabelecimento.id = estabelecimento.estabelecimetnopaiid))
SELECT e.e_data,
       lp.*
  FROM e
 INNER JOIN ESTABELECIMENTO_LOCAL_PRESCRICAO elp
    ON (e.id = elp.estabelecimentoid)
 INNER JOIN LOCAL_PRESCRICAO lp
    ON (lp.id = elp.localprescricaoid)
 ORDER BY e.rnum;

答案 1 :(得分:0)

使用子查询将分层查询的结果连接到其他2个表:

select lpad(' ',2*(x.level-1))     
              || x.estabelecimentoid      
              || ' ' || x.nomecompleto  
  from (select rownum r, level,
               , estabelecimento.id estabelecimentoid 
               , estabelecimento.nomecompleto nomecompleto
          from estabelecimento 
         where estabelecimento.activo = 1 
         start with estabelecimento.id = 36 
        connect by prior estabelecimento.id = estabelecimento.estabelecimetnopaiid
       ) x, 
       estabelecimento_local_PRESCRICAO elp, local_prescricao lp
 where lp.id = elp.local_prescricao_id 
   and x.estabelecimentoid = elp.estabelecimetnopaiid
order by r; -- to maintain ordering of the result the same as order of rows from 'x' subquery