There is a table with a tree (id, parent)
You need to write a query that returns for each node all child nodes and child nodes of all child nodes (recursively), as well as a column with a level in the tree of the current node and a column with a level in the tree of the child node. I wrote a request, but it hangs. It specifically hangs (it takes a very long time and I can not cancel it). In this case, errors with the achievement of the level of recursion 100 does not crash. That is, as I understand it, recursion does not go deep, but the execution of one iteration goes to infinity.
WITH Tree(Id,Parent,Level) AS ( SELECT Node_Id ,0 ,0 FROM CatalogOKPD WHERE Node_Parent_Id = 0 UNION ALL SELECT okpd.Node_Id ,okpd.Node_Parent_Id ,t.Level+1 FROM CatalogOKPD okpd JOIN Tree t ON t.Id = okpd.Node_Parent_Id) ,FullTree(Id,Child,Level,ChildLevel) AS ( SELECT t1.Id ,t2.Id ,t1.Level ,t2.Level FROM Tree t1 JOIN Tree t2 ON t1.Id=t2.Parent UNION ALL SELECT ft.Id ,t.Id ,ft.Level ,t.Level FROM Tree t JOIN FullTree ft ON t.Parent = ft.Child ) SELECT * FROM FullTree As a result, from a table with such data
id parent --- ------- 1 0 2 1 3 1 4 0 5 4 6 4 7 6 8 7 I want to get an answer
id child level childlevel ----------- ----------- ----------- ----------- 1 2 0 1 1 3 0 1 4 5 0 1 4 6 0 1 4 7 0 2 4 8 0 3 6 7 1 2 6 8 1 3 7 8 2 3 UPD:
corrected the request, checked on a small amount of data, all the rules. But on a real table with 70,000 entries, the request is unrealistically long. So it needs to be optimized (or rewritten otherwise)