0

I am trying to display hierarchical data with MariaDB (V.10.4.32-MariaDB) query, to show relationships,( like list of recipes, corporate org chart or program hierarchy). I can do some manipulation in PHP if required. In DB2 I can use CONNECT_BY_ROOT and CONNECT BY PRIOR to make these relationships, but MySQL does not support this vocabulary.

Example: Input

   Parent Child
    A        D
    B        E
    B        G
    E        H 

Output

1.     A
1.1      D
  
2.     B
2.1      E
2.1.1      H
2.2      G

The closest I get with MariaDB is by using a Common Table Expression:

WITH RECURSIVE hierarchy_cte AS (
    -- Anchor member: start with the root parent
    SELECT WHPNAM  as parent,
           WHFNAM  as child
    FROM rf_pgm_ref
    WHERE WHPNAM = 'ADDRESSR'  -- Starting parent

    UNION ALL

    SELECT 
           h.WHPNAM    as parent,
           h.WHFNAM    as child
        FROM rf_pgm_ref h
    INNER JOIN hierarchy_cte cte ON h.WHPNAM = cte.child
)
SELECT DISTINCT   parent, child
FROM hierarchy_cte
ORDER BY parent, child;
8
  • 1
    Please clarify whether you are using MySQL or MariaDB, and what version. Query SELECT VERSION(); and add the result to your question above. MySQL and MariaDB are different database products, and they are not compatible. You want a solution that will work on the database you are using, and solution for either MySQL or MariaDB may not be applicable to the other. Commented Jul 25, 2024 at 16:59
  • actually 10.4.32-MariaDB Commented Jul 25, 2024 at 17:04
  • 1
    some examples here that might be useful...mariadb.com/kb/en/recursive-common-table-expressions-overview Commented Jul 25, 2024 at 17:07
  • 1
    I've edited this post to make it more clear that you are not using MySQL. Commented Jul 25, 2024 at 17:08
  • 1
    This question is similar to: Implement Recursive CTE for Hierarchical Query to MariaDB. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Jul 25, 2024 at 17:23

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.