I am trying to display hierarchical data with MySQL (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 MySQL 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;