Рекурсивный запрос
Версия 2.9 от Alexandr Fokin на 2022/01/03 14:43
WITH RECURSIVE tree (nm, id, level, pathstr)
AS
(
--Первый элемент в выборке. Начало рекурсии
SELECT
nm,
id,
0,
cast('' as text)
FROM tree_sample
WHERE id_parent is null
UNION ALL
--Каждый последующий элемент рекурсии
SELECT
tree_sample.nm,
tree_sample.id,
t.level + 1,
tree.pathstr + tree_sample.nm
FROM tree_sample
INNER JOIN tree
on tree.id = tree_sample.id_parent
)
SELECT
id,
space(level) + nm as nm
FROM tree
ORDER BY pathstr
AS
(
--Первый элемент в выборке. Начало рекурсии
SELECT
nm,
id,
0,
cast('' as text)
FROM tree_sample
WHERE id_parent is null
UNION ALL
--Каждый последующий элемент рекурсии
SELECT
tree_sample.nm,
tree_sample.id,
t.level + 1,
tree.pathstr + tree_sample.nm
FROM tree_sample
INNER JOIN tree
on tree.id = tree_sample.id_parent
)
SELECT
id,
space(level) + nm as nm
FROM tree
ORDER BY pathstr
Рекурсивные SQL запросы
https://habr.com/ru/post/27439/