En approche descendante, la requête ancre sélectionne uniquement les racines, c’est-à-dire les éléments sans parent.
WITH RECURSIVE top_down AS (
SELECT id, parent, text
FROM test
WHERE parent IS NULL
UNION ALL
SELECT t.id, t.parent, concat_ws('/', r.text, t.text)
FROM test t
JOIN top_down r ON t.parent = r.id
)
SELECT id, text
FROM top_down
WHERE id = 4;En approche ascendante, on part de l’élément cible et on remonte vers la racine.
WITH RECURSIVE bottom_up AS (
SELECT id, parent, text
FROM test
WHERE id = 4
UNION ALL
SELECT r.id, t.parent, concat_ws('/', t.text, r.text)
FROM test t
JOIN bottom_up r ON r.parent = t.id
)
SELECT id, text
FROM bottom_up
WHERE parent IS NULL;