Oracle
 sql >> Base de Dados >  >> RDS >> Oracle

Como escrever subconsulta recursiva envolvida no sqlplus com várias tabelas para rastrear nós?


Em seu exemplo simplificado (mais ou menos, comecei a usar seus nomes de tabelas reais, mas são os dados originais), você pode obter todas as rotas por meio de vários switches com:
with rcte (rootsectionnumber, fromsectionnumber, tosectionnumber) as (
  select fromsectionnumber, fromsectionnumber, tosectionnumber
  from switchingdevice
  where normalswitchingdevicestate = 'CLOSED'
  union all
  select r.rootsectionnumber, sd.fromsectionnumber, sd.tosectionnumber
  from rcte r
  join switchingdevice sd on sd.fromsectionnumber = r.tosectionnumber
)
select rootsectionnumber, tosectionnumber from rcte;

ROOTSECTIONNUMBER TOSECTIONNUMBER
----------------- ---------------
               54             105
              105             106
              105             999
              999             700
               54             106
              105             500
               54             999
              105             700
               54             500
               54             700

um dos quais tem uma rota de ponta a ponta da seção 54 a 700; e você pode juntar isso à definição de carga:
with rcte (rootsectionnumber, fromsectionnumber, tosectionnumber) as (
  select fromsectionnumber, fromsectionnumber, tosectionnumber
  from switchingdevice
  where normalswitchingdevicestate = 'CLOSED'
  union all
  select r.rootsectionnumber, sd.fromsectionnumber, sd.tosectionnumber
  from rcte r
  join switchingdevice sd on sd.fromsectionnumber = r.tosectionnumber
)
select ld.loadnumber, t.transformernumber
from loaddefinition ld
join rcte r on r.rootsectionnumber = ld.sectionnumber
join transformer t on t.tosectionnumber = r.tosectionnumber
where ld.loadnumber = 100;

LOADNUMBER TRANSFORMERNUMBER
---------- -----------------
       100              5000

Ou se você precisar incluir o busnumber na lógica (com base em uma breve olhada em sua consulta maior...):
with rcte (rootsectionnumber, busnumber, fromsectionnumber, tosectionnumber) as (
  select fromsectionnumber, busnumber, fromsectionnumber, tosectionnumber
  from switchingdevice
  where normalswitchingdevicestate = 'CLOSED'
  union all
  select r.rootsectionnumber, r.busnumber, sd.fromsectionnumber, sd.tosectionnumber
  from rcte r
  join switchingdevice sd on sd.fromsectionnumber = r.tosectionnumber
  and sd.busnumber = r.busnumber
)
select ld.loadnumber, t.transformernumber
from loaddefinition ld
join rcte r on r.rootsectionnumber = ld.sectionnumber
and r.busnumber = ld.busnumber
join transformer t on t.tosectionnumber = r.tosectionnumber
and t.tobusnumber = r.busnumber
where ld.loadnumber = 100;

LOADNUMBER TRANSFORMERNUMBER
---------- -----------------
       100              5000

db<>fiddle

Adicionar suas outras tabelas obviamente complicará um pouco as coisas, mas não está claro como todas elas estão relacionadas.