Перенести Oracle CONNECT BY на postgresql 10 - PullRequest
2 голосов
/ 18 октября 2019

У меня есть этот SQL:

SELECT count(*) as ct
          FROM classifications cls
WHERE
   cls.classification_id = :classification_id
START WITH cls.classification_id = :root_classification_id
CONNECT BY NOCYCLE PRIOR cls.classification_id = cls.parent_id

, и мне нужно перенести его в postgresql 10.

Я уже установил расширение таблицы и попробовал с connectby. вот моя попытка:

SELECT count(*) as ct
          FROM classifications cls
WHERE
   cls.classification_id = :classification_id

union
                  SELECT count(classification_id) FROM connectby('classifications','classification_id','parent_id',:root_classification_id,5)
                  as t(classification_id varchar, parent_id varchar,level int) 

Проблема в том, что объединение является неправильным путем, потому что тогда вы получите 2 результата подсчета.

1 Ответ

2 голосов
/ 18 октября 2019

Нет необходимости использовать расширение tablefunc. Это легко сделать с помощью рекурсивного CTE

with recursive tree as (

  select cls.classification_id, cls.parent_id 
  from classifications cls
  where cls.classification_id = :root_classification_id

  union all

  select child.classification_id, child.parent_id
  from classifications child
     join tree parent on child.parent_id = parent.classification_id
)
select count(*)
from tree;

Первый запрос внутри CTE соответствует части start with из Oracle start with. И ПОДКЛЮЧЕНИЕ к CTE во втором запросе соответствует части connect by в запросе Oracle.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...