How to write this recursion? And how to design the corresponding structure?

there is a database as follows:

< table > < thead > < tr > < th > id < / th > < th > pid < / th > < th > name < / th > < / tr > < / thead > < tbody > < tr > < td > 1 < / td > < td > 0 < / td > < td > a < / td > < / tr > < tr > < td > 2 < / td > < td > 1 < / td > < td > b < / td > < / tr > < tr > < td > 3 < / td > < td > 2 < / td > < td > c < / td > < / tr > < tr > < td > 4 < / td > < td > 2 < / td > < td > d < / td > < / tr > < tr > < td > 5 < / td > < td > 1 < / td > < td > e < / td > < / tr > < tr > < td > 6 < / td > < td > 2 < / td > < td > f < / td > < / tr > < tr > < td > 7 < / td > < td > 5 < / td > < td > g < / td > < / tr > < tr > < td > 8 < / td > < td > 5 < / td > < td > h < / td > < / tr > < tr > < td >. < / td > < td >. < / td > < td >. < / td > < / tr > < / tbody > < / table >

pid: represents parent ID

get this data and how to code the tree result (json format) back to the front end.

{
    "id": 1,
    "name": "a",
    "children": [
        {
            "id": 2,
            "name: "b",
            "children": [
                {
                    "id": 3,
                    "name": "c",
                    "children": [ ... ] // 
                },
                {...},
                {...},
            ]
        },
        {
            "id": 5,
            "name": "e",
            "children": [
                {
                    "id": 7,
                    "name": "g"
                },
                {
                    "id": 8,
                    "name": "h"
                }
            ]
        },
    ]
}

there is no limit to the number of sons down, and there is only one node at the top.

Aug.16,2021

CTE, supported by mysql since 8.0 is easy to implement recursion. If you are not this version, then basically can not be written by SQL, change the stored procedure.

stored procedure reference: https://blog.csdn.net/moyanxu.

CTE reference:

  https://www.yiibai.com/mysql/.

Menu