Hierarchical MariaDB/MySQL recursive query (parent only)

3.7k views Asked by At

I have the following table and would like to write a proper SQL query in MariaDB / mySQL to return the results underneath.

"dirID" "parentID"  "name"
"1" "0" "C:\"
"2" "1" "\temp"
"3" "1" "\Users"
"4" "3" "\Jon"

dirID name
1     C:
2     C:\temp
3     C:\Users
4     C:\Users\John

So far I am trying to use CASE WHEN which I am pretty sure is way too inefficient and not the solution to the problem as follows:

cDir being the child dir and pDir being the parent:

SELECT
    cDir.dirID,
    cDir.parentID,
    cDir.name AS name,
    CASE
        WHEN cDir.parentID != 0 THEN ( SELECT pDir.name )
    END AS path
FROM dirs AS cDir
JOIN dirs AS pDir ON cDir.parentID = pDir.dirID

So at the end I want to do a CONCAT.

Any help? Thanks.

1

There are 1 answers

1
Julian Ladisch On

MariaDB and MySQL do not have a hierarchical/recursive query, but you can do a query with limited levels.

This is a query handling up to nine levels:

select d1.dirID, concat_ws('', d9.name, d8.name, d7.name,
    d6.name, d5.name, d4.name, d3.name, d2.name, d1.name) as name
from dirs d1
left join dirs d2 on d2.dirID=d1.parentID
left join dirs d3 on d3.dirID=d2.parentID
left join dirs d4 on d4.dirID=d3.parentID
left join dirs d5 on d5.dirID=d4.parentID
left join dirs d6 on d6.dirID=d5.parentID
left join dirs d7 on d7.dirID=d6.parentID
left join dirs d8 on d8.dirID=d7.parentID
left join dirs d9 on d9.dirID=d8.parentID

http://sqlfiddle.com/#!2/3b1c70/1