Saturday, July 29, 2017

MySQL: querying for hierarchical data for set number of levels

Problem: I have a table cherryshoetech that has hierarchical data, and needed to output out the name's of each record by each level (i.e. Level_1, Level_2, etc).

Environment:
MySql 5.7.10.0

Table Definition:
Columns     Type              Comments
---------       ------------      ----------------------------------------
id                int(11)           primary key
name          varchar(200)
type            varchar(20)
parent_id    int(11)           parent of this record, null if no parent

Solution:
Without using a stored procedure, and knowing that the hierarchical data can only go up to six levels, the below query works to output the 6 Levels by name:

-- We know we have at most six levels of cherryshoetech so only need to join up to 6 levels
SELECT
cst1.id, cst1.name AS Level_1, cst2.name as Level_2, cst3.name as Level_3, cst4.name as Level_4, cst5.name as Level_5, cst6.name as Level_6
FROM cherryshoetech cst1
LEFT JOIN cherryshoetech AS cst2 ON cst2.parent_id = cst1.id
LEFT JOIN cherryshoetech AS cst3 ON cst3.parent_id = cst2.id
LEFT JOIN cherryshoetech AS cst4 ON cst4.parent_id = cst3.id
LEFT JOIN cherryshoetech AS cst5 ON cst5.parent_id = cst4.id
LEFT JOIN cherryshoetech AS cst6 ON cst6.parent_id = cst5.id
ORDER BY
cst1.id

This article helped a lot.

No comments:

Post a Comment

I appreciate your time in leaving a comment!