MySQL Closure Table hierarchical database - How to pull information out in the correct order

前端 未结 1 646
悲&欢浪女
悲&欢浪女 2020-12-02 11:03

I have a MySQL database holding hierarchical data using the Closure Table method. A simple sample database create script follows the question. My issue at the moment is how

相关标签:
1条回答
  • 2020-12-02 11:33
    SELECT d.`iD`, d.`subsectionOf`,
           CONCAT(REPEAT('-', p.`len`), d.`name`) as hier,
           p.`len`, p.`ancestor`, p.`descendant`,
           GROUP_CONCAT(crumbs.`ancestor`) AS breadcrumbs
    FROM `TreeData` AS d
    JOIN `TreePaths` AS p ON d.`iD` = p.`descendant`
    JOIN `TreePaths` AS crumbs ON crumbs.`descendant` = p.`descendant`
    WHERE p.`ancestor` = 1
    GROUP BY d.`iD`
    ORDER BY breadcrumbs;
    
    +----+--------------+---------------------+-----+----------+------------+-------------+
    | iD | subsectionOf | hier                | len | ancestor | descendant | breadcrumbs |
    +----+--------------+---------------------+-----+----------+------------+-------------+
    |  1 |         NULL | Root A              |   0 |        1 |          1 | 1           | 
    |  2 |            1 | -Item 1             |   1 |        1 |          2 | 1,2         | 
    |  5 |            2 | --Item 1 Sub Item 2 |   2 |        1 |          5 | 1,2,5       | 
    |  6 |            2 | --Item 1 Sub Item 1 |   2 |        1 |          6 | 1,2,6       | 
    |  3 |            1 | -Item 2             |   1 |        1 |          3 | 1,3         | 
    |  4 |            1 | -Item 3             |   1 |        1 |          4 | 1,4         | 
    |  8 |            4 | --Item 3 Sub Item 1 |   2 |        1 |          8 | 1,4,8       | 
    |  9 |            4 | --Item 3 Sub Item 2 |   2 |        1 |          9 | 1,4,9       | 
    |  7 |            1 | -Item 4             |   1 |        1 |          7 | 1,7         | 
    +----+--------------+---------------------+-----+----------+------------+-------------+
    
    0 讨论(0)
提交回复
热议问题