79617211

Date: 2025-05-12 05:04:04
Score: 0.5
Natty:
Report link

Here's an option by using WITH RECURSIVE in an Items table having ItemID, Name and ParentID:

WITH RECURSIVE ItemsTree AS (
    -- Start with the given parent ItemID
    SELECT ItemID, Name, ParentID
    FROM Items
    WHERE ItemID = 50

    UNION ALL

    -- Recursively find children of each node
    SELECT i.ItemID, i.Name, i.ParentID
    FROM Items i
    INNER JOIN ItemsTree it ON i.ParentID = it.ItemID
)

-- Select all nodes in the tree under the given ItemID
SELECT *
FROM ItemsTree;

This one worked like a charm for me, returning not only the leaves but also all the mid-nodes of my hierarchical tree.

Reasons:
  • Blacklisted phrase (1): worked like a charm
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: nnimis